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 ^^
精彩评论