我正在使用Devise和CanCan来管理用户和用户权限。我想要的是:普通用户应该能够更新自己的帖子。最重要的模型称为活动。
在我为普通成员提供的能力模型中:
elsif user.role? :Member
can :read, :all
can :create, :all
can :manage, Activity, :user_id=>user.id
(感谢Yuriy Goldshtrakh第三行的语法)
在活动的索引视图中,我有:
<% if can? :update, activity %>
<br />
<%= link_to 'Update', edit_activity_path(activity) %>
<% end %>
<% if can? :delete, activity %>
<%= link_to 'Delete', activity, :confirm => 'Really?', :method => :delete %>
<% end %>
这有效:如果活动是由当前成员创建的,则它仅显示更新和删除链接。
但是,如果成员更新了活动,则不会保存更改,并且不会将成员发送回活动 - 就像成功更新后他/她应该保存的那样。
以下是活动控制器中的更新操作:
# PUT /activities/1.xml
定义更新
authorize! :update, @activity
@activity = Activity.find(params[:id])
respond_to do |format|
if @activity.update_attributes(params[:activity])
format.html { redirect_to(@activity, :notice => 'Activity was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @activity.errors, :status => :unprocessable_entity }
end
end
结束
问题是:为什么活动没有正确更新?我感谢所有的想法!
交换ActivitiesController#update
的第 1 行和第 3 行
def update
@activity = Activity.find(params[:id])
authorize! :update, @activity
...
end
您也可以使用Cancan的首选方式:load_and_authorize_resource
如果您的帖子和评论属于用户,您可以执行此操作
can :manage, [Post,Comment], :user_id=>user.id
例如能力:
if user.role?(:author)
can :create, Article
can :update, Article do |article|
article.try(:user) == user
end
end
尝试使用本教程:Railscasts CanCanCan。也许有帮助