Reputation: 6645
As we know, scopes starts load when calling. So this expression
articles = Article.published
articles.newest
gets 2 queries. Yes, we can do such this
articles = Article.published.newest
But what if I need conditions? If foo == bar than continue chain.
Upvotes: 2
Views: 1131
Reputation: 15056
You are incorrect. In your example, the two lines:
articles = Article.published
articles.newest
This will not generate two queries. The reason that you are able to continue chaining is that these calls will return an ActiveRecord::Relation
, which will only execute a query on traversal or a select few other method calls, like count, sum, or other aggregation methods.
If you are looking at this from the console, it will appear that each line is generating a query. This is because in the console, there is an implicit inspect
call being called after every evaluation, which will generate a query.
Upvotes: 11
Reputation: 24577
Conditions in the same table?
@a = Article.where("published = true AND foo = bar").order("publishing_date desc").limit(1)
If you need eager loading with multiple tables, use the includes(...)
method.
Upvotes: 0
Reputation: 160973
You could just do like below:
articles = foo == bar ? Article.published.newest : Article.published
Upvotes: 0