我正在使用RoR 4和Devise gem进行用户身份验证。我希望用户能够编辑自己的内容而不是其他人的内容。 authenticate_user方法似乎只是确保用户在编辑内容之前已登录。但是另一个用户可以注册并编辑其他人的内容。
我的控制器如下:
class PrayersController < ApplicationController
before_action :find_prayer, only: [:show, :edit, :updated, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
@prayers = Prayer.all.order("created_at DESC")
end
def show
end
def new
@prayer = current_user.prayers.build
end
def edit
end
def create
@prayer = current_user.prayers.build(prayer_params)
if @prayer.save
redirect_to @prayer, notice: "Successfully created prayer"
else
render 'new'
end
end
def update
@prayer = Prayer.find_by_id(params[:id])
if @prayer.update(prayer_params)
redirect_to @prayer, notice: "Prayer was successfully updated"
else
render 'edit'
end
end
def destroy
@prayer.destroy
redirect_to root_path
end
private
def prayer_params
params.require(:prayer).permit(:title, :body)
end
def find_prayer
@prayer = Prayer.find(params[:id])
end
end
我试图做一个像我这样的事情:
def own_prayer
if !current_user == Prayer.current_user
redirect_to @prayer, notice: "You cannot edit this prayer"
end
end
但那没用。我可以通过类似操作的视图限制对表单的访问,但我不认为这是完全安全的吗?
谢谢
答案 0 :(得分:1)
我猜你在current_user
课上没有上课方法Prayer
。您的用户模型中似乎也有has_many :prayers
。因此,要获得祷告的用户,您需要在祷告实例变量上调用user
方法。
它应该是这样的:
@prayer = Prayer.find params[:id]
unless current_user == @prayer.user
redirect_to(@prayer, notice: "You cannot edit this prayer") and return
end
如果您需要更棘手的限制规则,请使用cancan gem