0
我有2個控制器用戶和Rota。我希望用戶能夠創建自己的Rota,但只能編輯,顯示和銷燬自己的Rota。我需要能夠編寫代碼,以便我的rotum對象屬於用戶對象。屬於用戶對象的軌道rotum對象
ROTA控制器:
class RotaController < ApplicationController
respond_to :html, :xml, :json
before_action :set_rotum, only: [:show, :edit, :update, :destroy]
def edit
@rotum = @user.rota.find params[:id]
end
def index
@rota = Rotum.all
respond_with(@rota)
end
def show
respond_with(@rotum)
end
def new
@rotum = Rotum.new
respond_with(@rotum)
end
def edit
end
def create
@rotum = Rotum.new(rotum_params)
@rotum.save
respond_with(@rotum)
end
def update
@rotum.update(rotum_params)
respond_with(@rotum)
end
def destroy
@rotum.destroy
respond_with(@rotum)
end
private
def set_rotum
@rotum = current_user.rotums.find(params[:id])
if @rotum.nil?
render :html => "Not authorized", :status => 401
end
end
def rotum_params
params.require(:rotum).permit(:name, :email, :mobile, :category)
end
end
用戶控制器
class UsersController < ApplicationController
before_filter :authenticate_user!
after_action :verify_authorized
def index
@users = User.all
authorize User
end
def show
@user = User.find(params[:id])
authorize @user
end
def update
@user = User.find(params[:id])
authorize @user
if @user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
def destroy
user = User.find(params[:id])
authorize user
user.destroy
redirect_to users_path, :notice => "User deleted."
end
def edit
@rotum = @user.rota.find params[:id]
end
private
def secure_params
params.require(:user).permit(:role)
end
end
到目前爲止,我的羅塔允許任何人創建,顯示,編輯和刪除的ROTAS頁面上的羅塔。我只希望用戶能夠編輯他們創建的只有他們自己的rota。爲此,我被告知告訴rota對象屬於用戶對象。我如何在我的控制器或模型中執行此操作。
用戶模型
class User < ActiveRecord::Base
has_many :rota, dependent: :destroy
enum role: [:user, :vip, :admin]
after_initialize :set_default_role, :if => :new_record?
def set_default_role
self.role ||= :user
end
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
ROTUM模型
class Rotum < ActiveRecord::Base
belongs_to :user
end
我得到的錯誤:在/羅塔
NoMethodError/15
未定義的方法`rotums'爲#
香港專業教育學院把我在我的課已經編輯和編輯我上面的帖子給你看我的模型。我已經完成了你告訴我的內容,但是當我點擊Create Rotum或嘗試刪除現有的。它給了我/ rota/15undefined方法'rotums'的errorNoMethodError,用於#<用戶:0x00000005a7fcb0> @Fer – Rahid 2014-10-09 13:35:37
看起來像是發生在你的'rota_controller#set_rotum'中。你有一個@rotum = current_user.rotums ...使用@rotum = current_user.rota ...而不是 – Fer 2014-10-09 13:51:55
Hi @Fer我試過了,現在我得到錯誤,在'Where子句'中的未知列'rota.user_id' – Rahid 2014-10-09 15:37:07