我正在尝试使用 ActiveRecord 请求一些数据但没有成功。
我有这些模型:
部分有多个问题
问题有一个答案
一个答案属于一个用户和一个问题
所以我想请求指定的用户,所有带有链接问题和链接答案的部分。
也许是这样
Section.all.joins(:questions).joins(:answer).where(answer.user_id = USER_ID)
感谢您的帮助!
最佳答案
您可以执行以下操作:
Section.joins(questions: :answer).where(answers: { user_id: USER_ID })
一些要知道的事情:
- 在
joins
/includes
方法中,始终使用与关系完全相同的名称 - 在
where
子句中,始终使用关系的复数名称(实际上是表的名称,默认为复数形式的模型名称,但也可以手动设置)
例子:
# 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' })
#^^ ^
类似问题:
- 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
关于ruby-on-rails - 多个左连接与 rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827936/