cancan规则创建问题

时间:2010-11-29 23:28:24

标签: ruby-on-rails ruby security cancan railscasts

我有rails应用程序,其中包含以下模型 - 用户,博客,帖子,BlogMembership。

class BlogMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :blog

  # Membership types:
  SUBSCRIBER = 0
  AUTHOR = 1
  MODERATOR = 2
end

class Blog < ActiveRecord::Base
  has_many :posts
  has_many :memberships, :class_name => "BlogMembership"

  # Blog memberships
  def subscribers
    self.memberships.where(:membership_type => [BlogMembership::SUBSCRIBER, BlogMembership::AUTHOR, BlogMembership::MODERATOR]).collect(&:user)
  end

  def authors
    self.memberships.where(:membership_type => [BlogMembership::AUTHOR, BlogMembership::MODERATOR]).collect(&:user)
  end

  def moderators
    self.memberships.where(:membership_type =>  BlogMembership::MODERATOR).collect(&:user)
  end
end

在Ability类中(因为我使用cancan进行访问限制)我尝试限制用户和版主访问博客,但使用以下规则

if user.is? :moderator
  can :manage, Post do |post|
    post.blog.moderators.include? user
  end
end

所有用户都可以将帖子发送到任何博客。

请告诉我 - 如何在Ability类中为以下关系方案正确配置规则?

1 个答案:

答案 0 :(得分:0)

如果你尝试这种语法?

can :manage, Post do |action, post|
    post.blog.moderators.include? user
end