Reputation: 1332
I'm facing difficulty in understanding when do we hit the db in rails active record and when exactly are we building query.
users = User.where(org_id: 15) #db hit 1?
Is this going to hit db ?
users.where(is_suspended: false) #db hit 2?
Use full links/blogs would be helpful.
Upvotes: 0
Views: 1386
Reputation: 15838
None of the above acutally hit's the database unless you do something with them.
users = User.where(org_id: 15)
only creates an object that represents the query, if you run that line on a console, the interpreter will hit the database because it will try to render the collection, but if you run that inside a script it WON'T run the actual query.
Same for the second line, if you run users.where(....)
on the console, the interpreter will try to render the collection so it will hit the database, but inside a script it won't run the query until you actually do something with that.
You can check the server log to understand it better. If you do those two lines in your rails app, you won't see any query unless you do something like users.each do |user| ....
or users.first
or user.to_a
or something similar that actually requires the query to be run.
Upvotes: 4