如果我需要用户,如何添加cancan能力只能为他的帖子创建评论?

时间:2014-09-10 09:07:26

标签: ruby-on-rails ruby-on-rails-4 cancan

在我的应用程序中,用户创建帖子,其他具有角色“executor”的用户创建我使用cancan的注释,如果创建注释我需要做什么可以是具有角色“executor”的用户和创建帖子但无法创建注释的用户到其他帖子?

if user.has_role? :executor
    can :manage, [Responce, Comment]
  else
    can :read, :all
  end

if user.has_role? :customer
    can :manage, Post
    can :manage, Comment, :user => {user_id: user.id}
      else
    can :read, :all
  end

Comment.rb

class Comment < ActiveRecord::Base
    acts_as_nested_set :scope => :attachable

    belongs_to :attachable, :polymorphic => true
    has_many :comments, :as => :commentable
    belongs_to :user
end

class User < ActiveRecord::Base

    before_create :create_role


  has_many :posts
  has_many :comments, as: :attachable
  has_many :users_roles, dependent: :destroy
  has_many :roles, through: :users_roles


  def has_role?(role_sym)
    roles.any? { |r| r.name.underscore.to_sym == role_sym }
  end


  private
    def create_role
      self.roles << Role.find_by_name(:customer)  
    end
end

1 个答案:

答案 0 :(得分:1)

ability.rb

can :add, Comment, attachable: {user_id: user.id}
can [:update, :delete], Comment, user_id: user.id

在控制器中 CommentsCotroller

 @comment = Comment.new(com_params)
 authorize! :add, @comment = @comment