【问题标题】:Letting users update their own posts with CanCan and Devise让用户使用 CanCan 和 Devise 更新自己的帖子
【发布时间】:2012-05-02 18:30:47
【问题描述】:

我正在使用 Devise 和 CanCan 来管理用户和用户权限。 我想要的是:普通用户应该能够更新自己的帖子。 最重要的模型称为 Activity。

在我对普通会员的能力模型中:

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 %>

这有效:它只显示 更新和删除链接,如果 Activity 是由当前成员创建的。

但是,如果成员更新活动,则不会保存更改,并且不会将成员发送回活动 - 因为他/她应该在成功更新后。

这是活动控制器中的更新操作:

  # 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

结束

问题是:为什么活动没有正确更新? 我很感激所有的想法!

【问题讨论】:

    标签: ruby-on-rails devise cancan


    【解决方案1】:

    交换ActivitiesController#update的第1行和第3行

    def update
      @activity = Activity.find(params[:id])
    
      authorize! :update, @activity
      ...
    end
    

    你也可以使用the preferred way with Cancan:load_and_authorize_resource

    【讨论】:

    • 你是对的!这就是它不起作用的原因。非常感谢!
    【解决方案2】:

    如果您的帖子和 cmets 属于该用户,您可以这样做

    can :manage, [Post,Comment], :user_id=>user.id
    

    【讨论】:

      【解决方案3】:

      例如能力:

      if user.role?(:author)
              can :create, Article
              can :update, Article do |article|
                article.try(:user) == user
              end
            end
      

      试试这个教程:Railscasts CanCan 也许有帮助

      【讨论】:

        猜你喜欢
        • 2018-03-06
        • 1970-01-01
        • 1970-01-01
        • 2012-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多