我有一个特定的要求,其中视图有不同的内容基于用户的类型。假设我有针对用户控制器的index操作。然后,我可以使用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 deniedCancan需要一个额外的查询,不是吗?我可能用错了方法使用cancan。所以我需要一些建议。
下面是我的ability.rb文件的粗略片段
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发布于 2013-07-06 23:46:16
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'))https://stackoverflow.com/questions/8223949
复制相似问题