2010-09-13 81 views
0

我想在我的模型上创建一个范围,将可用结果限制为仅由用户的合作伙伴拥有的结果。但是,当用户是管理员时,我希望所有模型都可用。 这工作,但看起来很愚蠢。什么是适当的rails3表达方式?rails3是否有可能创建一个没有限制的model.scope

scope :accessible_by, proc { |user| 
    if user.admin? 
    where("1=1") 
    else 
    where(:owner_id => user.partner.id) 
    end 
} 

我希望能够做的是选择进一步做e.g

@models = MyModel. 
      accessible_by(current_user). 
      other_scope. 
      where(:property => value). 
      order("another_property desc"). 
      all 

回答

1

您可能能够使用所有的修改。

scope :accessible_by, proc { |user| 
    if user.admin? == false 
    where(:owner_id => user.partner.id) 
    end 
} 
+0

不知道#all。谢谢! – 2010-09-13 17:52:17

+0

尽管触发查询,并不让我进一步 – einarmagnus 2010-09-13 20:45:28

+1

甚至不需要所有。只是不指定其他条件。所有命名的作用域只是在ActiveRecord对象内激发一个方法。例如,如果user.admin? ==假,那么你想要触发where方法...否则你不需要在任何where子句上加上。 – davydotcom 2010-09-14 18:26:31

相关问题