Forum: Ruby on Rails Has_many association with named_scope?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jacob P. (Guest)
on 2009-05-10 17:59
(Received via mailing list)
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.
Frederick C. (Guest)
on 2009-05-10 18:29
(Received via mailing list)
On May 10, 2:58 pm, Jacob P. <removed_email_address@domain.invalid> wrote:
> What's going on here (and what am I doing wrong)?
>
Have you looked at the sql this is executing ?

Fred
Jacob P. (Guest)
on 2009-05-11 01:40
(Received via mailing list)
> 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
This topic is locked and can not be replied to.