views:

94

answers:

3

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 be equivalent:

@orders = @box.balls
@orders = @box.balls.green
A: 
default_scope :color, :conditions => { :color => "green"}

Use this

default_scope acts on whole model. But I need option that acts oonly on has_many association. I want to @box.balls to returns all balls with green color. And I want to Ball.all return all balls green and red.
petRUShka
A: 

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

Jesse Wolgamott
I want to set scope only for has_many assotiation. I want to @box.balls to returns all balls with green color. And I want to Ball.all return all balls green and red.
petRUShka
Indeed. So you'd have on the Ball model, "scope :red, where(:coulour=>'red')" ... then, @box.balls.red
Jesse Wolgamott
:)I want to avoid use scope by hand. I want to set default scope for has_many, is it possible?
petRUShka
You need to set scope in the /app/models/ball.rb ------- after that, you'll say "Ball.red" to find all red balls. You can say "@box.balls.red".... If you want to just call "@box.red_balls" then create a "red_balls" method on Box that balls @box.balls.red"
Jesse Wolgamott
A: 

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.

mdrozdziel