2010-09-29 62 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

相關問題