Scopes in ruby on rails
Reading through Rails Recipes: Rails 3 Edition I discovered a much better way of doing my searches.
In my multi-domain application, articles belong to sites, sites have many articles. I was finding articles that belonged to particular sites by doing
Articles.where("site_id = ?", site.id)
It's not too bad, but it gets a bit much writing out a lot of times.
Now, I've added a scope. In my article model I have
app/models/article.rb
class Article < ActiveRecord::Base
belongs_to :site
scope :by_site, lambda {|site| where(:site_id => site.id) }
end
Then you can write
Articles.by_site(site)
and get the same thing as before. Much clearer and also DRYer.