starwars25
starwars25

Reputation: 405

Active Record Query strange behavior

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?

Upvotes: 0

Views: 44

Answers (1)

spickermann
spickermann

Reputation: 107107

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.

Upvotes: 2

Related Questions