I had a confusion about how Ruby executes a query:
Lets suppose we have two methods:
def meet1
user = User.all
end
everytime I call this method I get a query running which says:
'User Load (18.3ms) SELECT "users".* FROM "users" INNER JOIN "roles" ON "roles"."user_id" = "users"."id" WHERE "users"."banned" = 'f' AND "roles"."description" = 'gogetter''
It means that it queries the users...
lets suppose I have another method:
def meet2
user = User.all
user.to_sql
end
when I call this it returned me the SQL format of that query:
So my question is in the first method the query gets executed but does the query gets executed in the second method? Or its just showing me the end result without executing the query because I never used it?
user = User.all
does nothing but create a potential query, and spawn
a copy of it into user
. This follows the "Builder Pattern"; user
could then say user.joins(...)
, or user.order(...)
, to build a different potential query. They both return a spawn
ed copy of the query.
What you do with meet1
triggers the actual hit to the database. I suspect that something as innocuous as p meet1
, or even your IRB shell, could evaluate the spawn
ed potential database query as an Enumeration
, which then hits the database.
I would like you too have a look at this answer
when you call
User.all
it returnsUser::ActiveRecord_Relation
object, and by itself this object does not issue a database query. It's where you use this object that matters.
so when meet1 is called it issues the query but in case of meet2
User.all
issues relational object and user.to_sql
issues the query related to database.
You can see same thing happens when you try to chain multiple filters based on condition
u = User.all
u = u.where(name: "Hello") if any_condition?
u = u.where(last_name: 'world') if any_other_condition?
in such cases the in any_condition? and any_other_condition? is true it does only one query merging all 3 thing .all and all the where conditions.
I would like you have a look at blog here it shows some kickers
methods which will make you a bit more clear about the way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With