Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Left join with rails 4

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 !

like image 622
bokzor Avatar asked Mar 25 '26 20:03

bokzor


1 Answers

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:

  • How to query a model based on attribute of another model which belongs to the first model?
  • association named not found perhaps misspelled issue in rails association
  • Rails 3, has_one / has_many with lambda condition
  • Rails 4 scope to find parents with no children
  • Join multiple tables with active records
like image 63
MrYoshiji Avatar answered Mar 28 '26 10:03

MrYoshiji