# Has\_many association with named\_scope?

**URL:** <https://www.ruby-forum.com/t/has-many-association-with-named-scope/167628>\
**Category:** Rails\
**Created:** [May 10, 2009, 3:59pm UTC](https://www.ruby-forum.com/t/has-many-association-with-named-scope/167628 "2009-05-10T15:59:13Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jacib](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/da6949/32.png) [@jacib](https://www.ruby-forum.com/u/jacib)\
**Post date:** [May 10, 2009, 3:59pm UTC](https://www.ruby-forum.com/t/has-many-association-with-named-scope/167628/1 "2009-05-10T15:59:13Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![jacib](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/da6949/32.png) [@jacib](https://www.ruby-forum.com/u/jacib)\
**Post date:** [May 10, 2009, 4:29pm UTC](https://www.ruby-forum.com/t/has-many-association-with-named-scope/167628/2 "2009-05-10T16:29:12Z")

</div>

On May 10, 2:58 pm, Jacob P. [removed\_email\_address@domain.invalid](mailto: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

---

<div class="post-metadata">

**Author:** ![jacib](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/da6949/32.png) [@jacib](https://www.ruby-forum.com/u/jacib)\
**Post date:** [May 10, 2009, 11:40pm UTC](https://www.ruby-forum.com/t/has-many-association-with-named-scope/167628/3 "2009-05-10T23:40:07Z")

</div>

> 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
