Reputation: 27852
If I have a User table and House table and I do this:
users = User.where(status: 3)
homes = Home.joins(:user).merge(users)
On the first assignation am I performing a query already? Or it waits until the second to perform the query? Or it does it when you actually try to access any of those results? How does Rails manage to know when to perform the query?
Upvotes: 1
Views: 1642
Reputation: 1800
The where
method returns an ActiveRecord::Relation
object, and by itself this object does not issue a database query. It's where you use this object that matters. join
method as well lazy loads the database query by utilising the associated table, but only loading the Home
table into memory as the associated User
table is not required. Afterwards you have merge
, what merge
method does is a simple way of using a named scope on a joined model. Something like
class Home < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :home
scope :available, ->{ where(available: true) }
end
Upvotes: 1