我有2个控制器User和Rota。我希望用户能够创建自己的Rota,但只能编辑,显示和销毁自己的Rota。我需要能够编码,以便我的rotum对象属于用户对象。
ROTA CONTROLLER:
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
到目前为止,我的rota允许任何人在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 MODEL
class Rotum < ActiveRecord::Base
belongs_to :user
end
我收到错误:
/ rota / 15
的NoMethodError#
的未定义方法`rotums'答案 0 :(得分:0)
您没有展示自己的模特,所以我假设您有has_many
关系
class User < ActiveRecord::Base
has_many :rota, dependent: :destroy
end
class Rotum < ActiveRecord::Base
belongs_to :user
end
然后在您的控制器中,您可以使用以下内容:
class UsersController < ApplicationController
....
def edit
@rotum = @user.rota.find params[:id]
end
请注意,如果用户正在试图编辑不属于他的旋转,则会引发ActiveRecord::RecordNotFound
异常。
您可以通过以下方式避免此问题:
class UsersController < ApplicationController
....
def edit
@rotum = @user.rota.find_by id: params[:id] # returns nil in case the record does not exist or does not belong to @user
redirect_to "somewhere", alert: 'You cannot edit this element' if @rotum.blank?
end