用户登录后,只有创建记录的用户才能销毁自己的记录。我应该在下面的代码中添加什么??
def destroy
@topic = Topic.find(params[:id])
@topic.destroy
flash[:notice] = "topic deleted!"
end发布于 2012-07-09 22:37:38
您正在寻找的不是真正的设计,而是像CanCan这样的授权解决方案。
Devise只能对用户进行身份验证,并验证他们是否已登录并处于活动状态。您需要的是一种确定用户是否有权删除此主题的方法。
当然,您可以像这样滚动您自己的代码:
def destroy
@topic = Topic.find(params[:id])
if @topic.user_id == current_user.id
@topic.destroy
flash[:notice] = "topic deleted!"
else
flash[:error] = "not allowed"
end
end(代码假设您在主题中设置了belongs_to :creator, :class_name => :user关联。但是你明白我的意思了)。
但是使用像CanCan这样的东西会让你的生活变得容易得多,并会将代码减少到如下所示:
def destroy
@topic = Topic.find(params[:id])
authorize! :destroy, @topic
@topic.destroy
flash[:notice] = "topic deleted!"
end您的能力文件(请参阅defining abilities)设置如下:
can :manage, Topic, :owner_id => user.idhttps://stackoverflow.com/questions/11396988
复制相似问题