Rails3: how to set default conditions to has_many
I have boxes and balls. Balls are in boxes. Ball can be either red and green.
class Box < ActiveRecord::Base
has_many :balls
end
class Ball < ActiveRecord::Base
belongs_to :box
scope :green, where(:color => "green")
end
I want to set has_many only with green balls. I know that finder_sql method exists, but i don't know how to set via scopes.
I want that following examples to 开发者_如何学Gobe equivalent:
@orders = @box.balls
@orders = @box.balls.green
You can always use:
has_many :balls, :conditions => { :color => "green" }
It works in Rails3, but I am not sure if this syntax won't be deprecated due to some ActiveRecord::Relation equivalent. In the official documentation relased with Rails3 this syntax is still available, so I guess this stays out like it was in 2.3.x branch.
And in Rails 3, it's changed slightly:
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
This is an old question, but I was just looking to do the same thing, and I came across this question while searching. I never found a solution, but I came up with something that works well.
For your example, you can do this:
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
I'm not aware of the implications of doing this, but after some initial testing, it appears to work without issue. There are other values that can be set, like eager_load_values
, join_values
, order_values
, etc.
default_scope :color, :conditions => { :color => "green"}
Use this
精彩评论