【问题标题】:Using cancan the proper way正确使用cancan
【发布时间】:2011-11-22 08:34:08
【问题描述】:

我有一个特定的要求,即视图根据用户类型具有不同的内容。假设我有用户控制器的索引操作。然后我可以使用cancan来授权这样的动作

authorize! :index, @users

为了进一步过滤内容,我有另一个授权,比如

if can :view_all,User

进一步的另一个授权,例如

if can :view_some,User 将需要另一个。

这会导致很多条件。而不是这个,我可以只使用简单的条件,比如

If the user is with view_all access show him all 
else if the user is with view_some access show him some
else access denied

Cancan 需要一个额外的查询,不是吗?我可能以错误的方式使用cancan。所以需要一些建议。

这是我的ability.rb文件的粗略sn-p

    can :index, User do |user1|
      role.accesses.include?(Access.where(:name => "access1").first) || role.accesses.include?(Access.where(:name => "access2").first)
    end

    can :view_all, User do |user1|
      role.accesses.include?(Access.where(:name => "access1").first) 
    end

    can :view_some, User do |user1|
      role.accesses.include?(Access.where(:name => "access2").first) 
    end

【问题讨论】:

  • 你能告诉我们你的能力吗.rb?
  • 请将您已回答的其他问题标记为已回答。

标签: ruby-on-rails cancan


【解决方案1】:

Cancan 需要一个额外的查询?

在组合能力时,cancan 将使用单个查询。

如果您查看规格,例如。 spec/cancan/model_adapters/active_record_adapter_spec.rb,你会发现这样的规格:

it "should fetch any articles which are published or secret", focus: true do
  @ability.can :read, Article, :published => true
  @ability.can :read, Article, :secret => true
  article1 = Article.create!(:published => true, :secret => false)
  article2 = Article.create!(:published => true, :secret => true)
  article3 = Article.create!(:published => false, :secret => true)
  article4 = Article.create!(:published => false, :secret => false)
  Article.accessible_by(@ability).should == [article1, article2, article3]
end

如果你打开 SQL 日志记录,你会看到查询结合了条件:

Article Load (0.2ms)  
SELECT "with_model_articles_95131".* 
FROM "with_model_articles_95131" 
WHERE (("with_model_articles_95131"."secret" = 't') 
  OR ("with_model_articles_95131"."published" = 't'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    相关资源
    最近更新 更多