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 !
You can do the following:
Section.joins(questions: :answer).where(answers: { user_id: USER_ID })
Some stuff to know:
joins/includes method, always use the exact same name as the relation 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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With