ActiveRecord — Query all and include association which meets condition

五迷三道 提交于 2019-12-24 11:37:53

问题


Environment: Rails 3.2.22

Question:

Lets say I have the models Topics, Posts, and User.

Posts belongs to Topics User has many Posts

I want to make a query of Topic.all, but includes all posts associated to a user.

I've tried include and eager_load with a where condition for the user id, but only topics with a post which meets the condition are return.

What I want is all topics return and include only posts which match the user_id condition.


回答1:


After playing around with ActiveRecord I figured out how to do the query. It requires the left join as pointed out by @pshoukry, but it is missing two items.

  1. AND statement is required to include only posts for a specific user.
  2. An ActiveRecord method select needs to be appended at the end to include the fields you want.

To include all fields:

Topic.joins("LEFT JOIN posts ON posts.topic_id = topics.id AND posts.user_id = ?", user.id).select('topics.*, posts.*')

Now for the caveat. For those using Postgres and on Rails version 3.2.* there is a bug where the joined table will only return strings for ALL columns, disregarding the data type set. This issue is not present with Rails 4. There was an issue posted in the Rail's Github repo, but I can't seem to locate it. Since 3.2 is no longer supported they have no intention of fixing it.




回答2:


Try using left join in your relation

Topic.joins("LEFT JOIN posts ON topics.id = posts.topic_id")


来源:https://stackoverflow.com/questions/32661804/activerecord-query-all-and-include-association-which-meets-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!