开发者

How do I force ActiveRecord to load a belongs_to-has_one relation through a JOIN instead of 2 queries?

开发者 https://www.devze.com 2023-04-12 20:22 出处:网络
I have the following models: User < ActiveRecord::Base belongs_to :person end Person < ActiveRecord::Base

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:

开发者_Go百科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?


I found out that using:

User.includes(:person)

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

User.includes(:person).where('person.name=?', 'something')

I never cease to be amazed by Rails ^^

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号