Ruby on Rails Thursday, June 11, 2015

I would not recommend using a default scope on an ActiveRecord model for sorting.

Start your Rails console and try Model.find(1). This will result into: SELECT models.* FROM models WHERE models.id=1 ORDER BY id DESC LIMIT 1

This ORDER BY will be included in every unneccessary query. The above query will be slower in MySQL than without the ORDER BY clause. Try it yourself!

Create a normal scope and include it with every query where you expect more than 1 record as a result.

In case you consider a mixin try http://api.rubyonrails.org/classes/ActiveSupport/Concern.html


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/a472a643-672c-40f9-9d81-4678a236cc5d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment