Working with Ruby on Rails Models
I am new to ruby on rails and have a (probably simple) question regarding performance and best-practice for Rails 3. I am using a blog engine called enki blog, and I see that the person who wrote this blog engine is selecting tags using the following technique:
Tag.find(:all).reject {|tag| tag.taggings.empty? }.sort_by {|tag| tag.taggings_count }.reverse
I see no purpose of the ".reject" since empty tags are removed any time an article is created, updated, or destroyed. Assuming I am开发者_运维知识库 right about that, would this be a better approach?
Tag.find(:all, :order => "taggings_count desc")
I am looking for performance and readability. What is the best way to drill-down the results of a model? Is there any real difference between ".sort_by" and passing :order as a parameter?
Thanks in advance for any answers.
You're correct, that is definitely some inefficient code.
There is a significant difference between sort_by and :order. :order is used to build the SQL statement, meaning the database sorts the records before it returns them. sort_by is a Ruby method which rearranges the records the database has already returned. Generally the database is going to be much faster, so user :order.
I can't speak as to whether reject is necessary or not. But if it is, again it would be much quicker to do it in the database with a WHERE statement. So you would have
Tag.find(:all, :conditions => "taggings_count > 0", :order => "taggings_count desc")
In Rails 3 that would look like
Tag.where('taggings_count > 0').order('taggings_count desc')
精彩评论