如何强制 ActiveRecord 通过 JOIN 而不是 2 个查询来加载 Belongs_to-has_one 关系?
我有以下模型:
User < ActiveRecord::Base
belongs_to :person
end
Person < ActiveRecord::Base
has_one :user
end
如果我希望用户在加载时加载 Person,我会这样做:
User.includes(:person)
问题是使用 2 个查询,这很好,在belongs_to-has_many 关系中,但在这种情况下我认为最好使用 JOIN 和一个查询。
如果我执行 User.join(:person)
,它将加入 :person
但没有 select 语句并作为 :user
的属性。
我该怎么做?
I have the following models:
User < ActiveRecord::Base
belongs_to :person
end
Person < ActiveRecord::Base
has_one :user
end
If I wanted the User to be loaded with the Person when it is loaded I would do this:
User.includes(:person)
The problem is that that use 2 queries, which is fine, in a belongs_to-has_many relationship, but in this occasion I think it would be better to use a JOIN and just one query.
If I do User.join(:person)
it will join the :person
but withtout the select statment and as attributes of :user
.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现 using:
执行 2 个查询...但是,如果您需要在查询中使用 :person 列,ActiveRecord 会自动检测到它并使用连接将 2 个查询转换为单个查询,
我对此始终感到惊讶铁轨^^
I found out that using:
executes 2 queries... BUT, if you need to use a column of :person on the query, ActiveRecord automagically detects it and converts the 2 queries in a single query with joins
I never cease to be amazed by Rails ^^