2010-07-12 20 views
3

我有盒子和球。球在箱子裏。球可以是紅色和綠色。Rails3:如何設置默認條件爲has_many

class Box < ActiveRecord::Base 
    has_many :balls 
end 

class Ball < ActiveRecord::Base 
    belongs_to :box 
    scope :green, where(:color => "green") 
end 

我想只用綠色的球設置has_many。我知道finder_sql方法存在,但我不知道如何通過範圍設置。

我想那下面的例子是等價的:

@orders = @box.balls 
@orders = @box.balls.green 

回答

-1
default_scope :color, :conditions => { :color => "green"} 

使用此

+2

default_scope在整個模型上起作用。但是我需要只對has_many關聯起作用的選項。我想@ box.balls以綠色返回所有球。我想Ball.all所有的球返回綠色和紅色。 – petRUShka 2010-07-12 17:03:46

+2

不要使用它。每次我用'default_scope'我都後悔了。請注意,與此錯誤特徵相關的[很多潛在的槍支](http://pragdave.blogs.pragprog.com/pragdave/2012/03/be-careful-using-default_scope-and-order.html) 。 – 2013-05-15 02:44:10

2

而且在Rails 3中,它的微變:

class Item 
    scope :red, where(:colour => 'red') 
    scope :since, lambda {|time| where("created_at > ?", time) } 
end 

red_items = Item.red 
available_red_items = red_items.where("quantity > ?", 0) 
old_red_items = Item.red.since(10.days.ago) 

Credit and more information

+0

我想爲has_many assotiation設置範圍。我想@ box.balls以綠色返回所有球。我想Ball.all所有的球返回綠色和紅色。 – petRUShka 2010-07-12 17:02:12

+0

確實。所以你應該在球模型上,「範圍:紅色,其中(:coulour =>'紅色')」...然後,@ box.balls.red – 2010-07-12 17:53:18

+0

:) 我想避免使用範圍。我想爲has_many設置默認範圍,可以嗎? – petRUShka 2010-07-12 21:06:59

7

您可以隨時使用:

has_many :balls, :conditions => { :color => "green" } 

它工作在Rails3中,但我不知道這句法不會因一些的ActiveRecord ::關係相當於被棄用。在使用Rails3的官方文檔中,這種語法仍然可用,所以我想這個語法和2.3.x分支一樣。

+2

請注意,你會爲了清晰起見,可能想要調用關聯:green_balls。 – Eric 2013-01-16 04:01:54

0

這是一個老問題,但我只是想做同樣的事情,而我在搜索時遇到了這個問題。我從來沒有找到一個解決方案,但我想出了一些運作良好的東西。

對於你的榜樣,你可以這樣做:

class Box < ActiveRecord::Base 
    has_many :balls do 
    def self.extended(base) 
     base.where_values += Ball.green.where_values 
    end 
    end 
end 

class Ball < ActiveRecord::Base 
    belongs_to :box 
    scope :green, where(:color => "green") 
end 

我不知道這樣做的影響,但一些初步測試後,它似乎沒有問題的工作。還有其他值可以設置,如eager_load_values,join_values,order_values等。