3

I'm trying to request some data with ActiveRecord with no success.

I have these models :

Sections have multiple Questions

Questions have one Answer

One Answer belongs to one User and one Question

So I would like request for a specified user, all Sections with linked Questions et linked Answer.

Maybe something like

Section.all.joins(:questions).joins(:answer).where(answer.user_id = USER_ID)

Thanks for any help !

bokzor
  • 413
  • 7
  • 19

1 Answers1

4

You can do the following:

Section.joins(questions: :answer).where(answers: { user_id: USER_ID })

Some stuff to know:

  • In the joins/includes method, always use the exact same name as the relation
  • In the where clauses, always use the pluralized name of the relation (actually, the table's name, which is by default the model name in plural but can also be manually set)

Examples:

# Consider these relations:
User has_many :posts
Post belongs_to :user

# Usage of joins/includes & where:
User.includes(:posts).where(posts: { name: 'BlogPost #1' })
                  #^            ^
Post.joins(:user).where(users: { name: 'Little Boby Table' })
              #^^           ^

Similar questions:

Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
  • If you have again a few minutes. Can you explain this : questions: :answer Why first colon is a the end and the second one at the beginning ? – bokzor Apr 23 '15 at 16:08
  • it is the new ruby hash syntax. It is exactly the same to use `{ :questions => :answer }` and `{ questions: :answer }` (key is a symbol, value is a symbol in both examples). (The new syntax has been integrated to Ruby 1.9.x and newer versions – MrYoshiji Apr 23 '15 at 16:19
  • It seems it only returns the first Section. Is it possible to user a left join for, the Answer join ? – bokzor Apr 23 '15 at 16:51
  • Because, if there is not Answer. The request will return nothing – bokzor Apr 23 '15 at 17:00
  • use `includes` instead of the `joins` and the Section without answer(s) should be displayed – MrYoshiji Apr 23 '15 at 17:19
  • You get a +1 for Little Boby table, though I believe it was Little Bobby Drop Tables? – David Routen Oct 17 '16 at 03:22