Forum: Ruby on Rails how do collections from associations access class methods?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
3ea25dccef5fb82bdcc890236e68faff?d=identicon&s=25 altay (Guest)
on 2007-04-18 02:02
(Received via mailing list)
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!


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)
558:         configure_dependency_for_has_many(reflection)
560:         if options[:through]
561:           collection_reader_method(reflection,
562:         else
563:           add_multiple_associated_save_callbacks(
564:           add_association_callbacks(,
565:           collection_accessor_methods(reflection,
566:         end
568:         add_deprecated_api_for_has_many(
569:       end
This topic is locked and can not be replied to.