Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails How to get all the grandchildren of an ojbect

I have 3 models:

User
has_many :questions
has_many :corrections
end

Question
has_one :correction
belongs_to :user
end

Correction
belongs_to :user
belongs_to :question

So if user Bob asks a question then user Terry can check it and if its wrong offer a correction.

Lets stay with bob and assume he as kindly corrected 5 other users, i.e and lets assume he has been lucky to get 3 corrections from other users.

I want to be able to do something like this

@bob.corrections_offered => 5 correction objects @bob.corrections_received => 3 correction objects

the first one is easy as its really just @bob.corrections under the hood. But I dont know how to implement the latter one. Can anyone help?

UPDATE

So I tried using through as suggested like so (Oh and actually the question model above is actually called Sentence in my code. I.e. User => Sentence => Correction. )

has_many :sentences
has_many :corrections_received, :through => :sentences, :class_name => 'Correction'

but got this error in console

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :Correction in model Sentence. Try 'has_many :corrections_received, :through => :sentences, :source => '. Is it one of :language, :correction, :user, or :checker?

So tried the following

has_many :corrections_received, :through => :sentences, :source => :correction 

but got

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_one for has_many :corrections_received, :through => :sentences. Use :source to specify the source reflection.

not sure whats going wrong...

like image 301
robodisco Avatar asked Jan 22 '23 22:01

robodisco


2 Answers

You can add a has_many through relationship in your user model like so

class User
  #your usual relationships
  has_many :corrections_received, :through => :questions, :class_name => 'Correction'
end
like image 57
nas Avatar answered Jan 24 '23 13:01

nas


Try the following way:

has_many :corrections_received,:class_name=>'Correction',:conditions=>...
like image 21
psjscs Avatar answered Jan 24 '23 11:01

psjscs