ActiveRecord的 - 所有的查询,包括联想,符合条件 [英] ActiveRecord — Query all and include association which meets condition
问题描述
环保:Rails的3.2.22
Environment: Rails 3.2.22
问题
可以说我有这些模型主题
,文章
和用户
。
Lets say I have the models Topics
, Posts
, and User
.
文章
属于主题
用户
有许多文章
我要让 Topic.all
的查询,但包括与用户相关联的所有帖子。
I want to make a query of Topic.all
, but includes all posts associated to a user.
我已经试过包括
和 eager_load
用WHERE条件的用户ID,但只有一个主题后符合条件的回报。
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.
我要的是所有主题返回,并只包括其中符合条件的user_id帖子。
What I want is all topics return and include only posts which match the user_id condition.
推荐答案
与ActiveRecord的玩弄后,我想通了,该怎么办查询。它要求在左侧合并为指出@pshoukry,但它缺少两个项目
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.
-
和
语句需要包含特定用户的唯一的帖子。 - 在一个ActiveRecord方法
选择
需要在最后追加到包括你想要的字段。
AND
statement is required to include only posts for a specific user.- An ActiveRecord method
select
needs to be appended at the end to include the fields you want.
要包括所有字段:
Topic.joins(LEFT JOIN的帖子ON posts.topic_id = topics.id和posts.user_id =?,user.id)。选择(主题。*,发贴。*)
现在的告诫。对于那些使用Postgres的和on Rails的3.2版本。*有一个错误的地方连接表将只返回一个字符串所有列,无视数据类型集。这个问题是不是present使用Rails 4.被张贴在铁的Github上回购的问题,但我似乎无法找到它。由于3.2不再支持他们无意将其固定的。
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.
这篇关于ActiveRecord的 - 所有的查询,包括联想,符合条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!