0

The situation is on the screenshot below:

enter image description here

As you see, I call Property.limit(10) to grab first 10 objects from the database, but the query will execute only if I call @properties variable. I don't understand why it is not called. It then will be called in the view and slow up rendering. Surprisingly,it will be called in _filter partial, however, it doesn't contain @properties variable at all. What's going on?

enter image description here

At the same time, City.all and Country.all are executed in the controller. How can it happen?

1 Answer 1

2

Property.limit(10) does not load 10 properties from the database like you expect. It only returns a ActiveRecord::Relation.

The database query happens when you call a method on that Relation object that actually needs the data from that database (like calling count or each).

This is default ActiveRecord behavior. It does not slow down anything, because it does not affect the overall response time if the data loaded in the controller or in the view.

Read more about Relations and Lazy Evaluation.

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

1 Comment

This is the reason why you can chain multiple active record queries and the way by which ActiveRecord is able to merge all the queries into a single query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.