範圍,我有兩個範圍梁2合併條件模型
named_scope :by_foo, lambda { |foo| { :conditions => {:foo => foo} } }
named_scope :by_bar, lambda { |bar| { :conditions => ["bar like ?", bar+"%"] } }
我怎麼能在一起在一個範圍內,而不鏈混?
named_scope :by_baz # what that should look like ?
範圍,我有兩個範圍梁2合併條件模型
named_scope :by_foo, lambda { |foo| { :conditions => {:foo => foo} } }
named_scope :by_bar, lambda { |bar| { :conditions => ["bar like ?", bar+"%"] } }
我怎麼能在一起在一個範圍內,而不鏈混?
named_scope :by_baz # what that should look like ?
named_scope :by_baz, lambda {|args| by_foo(args[:foo]).by_bar(args[:bar])}
您可以通過調用它:
Model.by_baz({:foo=>value, :bar=>value})
這樣,只要你喜歡,不重寫條件,你可以添加儘可能多的範圍。
named_scope :by_foo_and_bar, lambda { |foo, bar| { :conditions => ["foo = ? AND bar like ?", foo, bar+"%"] } }
謝謝,但這代表重複代碼,當您更改其中一個輸入範圍時,您也需要重寫此代碼 – astropanic 2012-03-21 08:51:00
非常可讀和乾燥的解決方案,真棒,thx – astropanic 2012-03-21 08:50:00