Has_many association with named_scope?

In my Rails 2.3.2 app, I’m encountering a strange situation with
regards to named_scopes and associated objects.

I’ve got two models, Account and Openings:

class Account < ActiveRecord::Base

has_many :openings

end

class Opening < ActiveRecord::Base

belongs_to :account

named_scope :for_day_of_week, lambda { |dow| {:conditions =>
[‘day_of_week = ?’, dow] } }

end

With an account record and two opening records in the database, I can
do this:

OpeningHour.count
=> 2
OpeningHour.for_day_of_week(‘Monday’).size
=> 2
@account = Account.find(:first)
@account.opening_hours.size
=> 2
@account.opening_hours.for_day_of_week(‘Monday’).size
=> 0

It’s that last one, @account.opening_hours.for_day_of_week
(‘Monday’).size, that’s throwing me. I thought that the Opening
named_scope should filter the @account’s opening_hours, no?

What’s going on here (and what am I doing wrong)?

thanks very much,

Jacob P.

On May 10, 2:58 pm, Jacob P. [email protected] wrote:

What’s going on here (and what am I doing wrong)?

Have you looked at the sql this is executing ?

Fred

Have you looked at the sql this is executing ?

Thanks for the debugging tip, Fred. Of course the error was right
there in the SQL logs – the account_id wasn’t being set properly.

thanks again,

Jacob