# How do collections from associations access class methods?

**URL:** <https://www.ruby-forum.com/t/how-do-collections-from-associations-access-class-methods/92304>\
**Category:** Rails\
**Created:** [April 18, 2007, 2:02am UTC](https://www.ruby-forum.com/t/how-do-collections-from-associations-access-class-methods/92304 "2007-04-18T02:02:47Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![altay](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/51bf81/32.png) [@altay](https://www.ruby-forum.com/u/altay)\
**Post date:** [April 18, 2007, 2:02am UTC](https://www.ruby-forum.com/t/how-do-collections-from-associations-access-class-methods/92304/1 "2007-04-18T02:02:47Z")

</div>

Hi all-

I’m working on a little survey app. Basically, you can write and tag  
questions (using acts\_as\_taggable\_on\_steroids) and it serves these  
question to the user in random order.

I’ve defined a class method that returns a random question  
(self.randomq in the Question model).

I’ve also set up a has\_many :through association in the User model:  
has\_many :answered\_questions, :through =\> :responses, :source  
=\> :question

Now, let’s say I get an array of questions through the association,  
like so:

u = User.find(:first)  
u\_questions = u.answered\_questions =\> array of Question objects  
q = u\_questions.randomq =\> works! this collection can access the  
Question class methods.

However, if I _don’t_ get my collection of questions through an  
association, it barfs:

foo\_questions = Question.find\_tagged\_with( “foo” ) =\> array of  
Question objects  
foo\_questions.randomq =\> “no method” error. this collection can’t  
access the Question class methods.

Why is this? It it possible for me to hack the find\_tagged\_with  
method to make this work?

Thanks a ton!

Altay

P.S. I’m guessing, but not sure, that it has something to do with  
collection\_reader\_method (in line 561 of associations.rb, see below),  
but I’m a little too n00b to decipher the magic:

555: def has\_many(association\_id, options = {}, &extension)  
556: reflection = create\_has\_many\_reflection(association\_id,  
options, &extension)  
557:  
558: configure\_dependency\_for\_has\_many(reflection)  
559:  
560: if options[:through]  
561: collection\_reader\_method(reflection,  
HasManyThroughAssociation)  
562: else  
563: add\_multiple\_associated\_save\_callbacks(reflection.name)  
564: add\_association\_callbacks(reflection.name,  
reflection.options)  
565: collection\_accessor\_methods(reflection,  
HasManyAssociation)  
566: end  
567:  
568: add\_deprecated\_api\_for\_has\_many(reflection.name)  
569: end
