【发布时间】:2023-04-08 04:15:01
【问题描述】:
我有 2 个控制器 User 和 Rota。我希望用户能够创建自己的 Rota,但只能编辑、显示和销毁他们自己的。我需要能够编码,以便我的 rotum 对象属于用户对象。
旋转控制器:
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 对象属于用户对象。我怎样才能在我的控制器或模型中做到这一点。
用户模型
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
旋转模型
class Rotum < ActiveRecord::Base
belongs_to :user
end
我得到错误:
/rota/15 处的 NoMethodError
用于#的未定义方法“rotums”
【问题讨论】:
标签: ruby-on-rails ruby devise controller