2010-09-29 58 views
1

有没有写这个ActiveRecord的混合条件+更好的方式来写这个

一个更好的办法,我有一个条件,其以前看起来非常干净,很容易理解 像

Account.first.websites.last.users.find(:all, 
      :conditions => {:country => "XYZ",:status => "Single",:admin => nil) 

现在的大问题是不是拿起admin = false的用户。

即我希望来自特定国家的所有用户的状态为 “单一”,而管理员要么是“无”(数据库中为空)或“假”。

我设法得到想要的代码,但似乎并不满意它的清晰度 。

Account.first.websites.last.users.find(:all, 
    :conditions => ["country = ? AND status = ? AND admin IS NULL OR 
     admin = ?","XYZ","Single","false"]) 

任何帮助,将不胜感激。

感谢

+0

如何使用命名范围来澄清一切? – marcgg 2010-09-29 10:13:29

回答

1

我想补充一些范围,以模型:

scope :not_admin, where("admin is null or admin = ?", false) 
scope :single, where("status = ?", "single") 
scope :from_country, lambda {|country| where("country = ?", country} 

然后用它的控制器:

Account.first.websites.last.users.from_country("XYZ").single.not_admin 

你可以也使用自动生成范围:

Account.first.websites.last.users.scoped_by_country("XYZ").scoped_by_status("single").not_admin 

这里我只留下not_admin范围。

1

尝试以下操作:

Account.first.websites.last.users.all(:conditions => ["country = ? AND status = ? AND admin != true","XYZ","Single"]) 
+0

您可能需要使用'admin!=?'并添加一个'true'参数。 – Shadwell 2010-09-29 10:02:16

相关问题