我试图创建一个系统来检查当前用户是否有权编辑记录。我想这样做的方法是将@user的变量赋值给显示记录的链接ID和重定向的私有函数,除非@user
= current_user
,但是当我这样做时,我每次都会得到重定向行为(即使在用户拥有该记录)。基于Rails中的链接表字段分配一个实例变量
这里是控制器设置
def edit
@deal = Deal.find(params[:id])
@user = User.where(params[:id] === @deal.user_id)
correct_user
end
...
private
def correct_user
unless @user === current_user
redirect_to root_path
flash[:error] = 'You can only edit deals that you own'
end
end
用户和交易模型是通过有许多相关的,拥有
class User < ApplicationRecord
has_many :deals
...
class Deal < ApplicationRecord
belongs_to :user
而对于交易的模式(用户ID是在创建分配给user_id
)
create_table "deals", force: :cascade do |t|
t.text "headline"
t.string "matter"
t.text "summary"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_id"], name: "index_deals_on_user_id"
end
该项目设置与设计,所以这些助手是 也提供。
这得到了它,谢谢! – oneWorkingHeadphone