0

In the following block of code, on what line is the SQL actually executed on the database?

first_name, last_name = @name.split(", ")
people = Person.where(first_name: first_name)
people = people.limit(5)
people.each do |person|
  puts person
end

Thanks

1
  • Did my answer help you? Commented Feb 5, 2016 at 9:56

1 Answer 1

4

SQL query is executed in people.each do |person| line because only then Rails need the result of this query. Rails execute SQL only when it's literally needed, not when you build your scope. It's called lazy loading.

Sign up to request clarification or add additional context in comments.

2 Comments

But should it be in line 2 and line 3. Can you explain your answer pls.
I edited my answer. No, it should not be in line 2 and line 3 because rails don't need the result of this query in these lines.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.