Peel me a Grape :: We make things work

We Make Things Work :: Blog

Noel Rappin blogs with some great examples of how awsome named_scope is. It’s probably my most used feature in rails 2.1 so far. In excitement I neglected to read the docs or source until yesterday… I stumbled upon rails-doc the new kid on the block of rails doc apps. I realised you can use named_scopes with has_many associations. Sweet!!

I started off going nuts with named_scopes and lambda’s, now realising I can delete lots of code and make use of my association proxies instead.

class Post < ActiveRecord::Base
  belongs_to :user
  named_scope :by_user, lambda {|user| {:conditions=> {:user_id => user.id}}}
  named_scope :recent, {:limit => 10, :order => 'created_at desc'}
end

class User < ActiveRecord::Base
  has_many :posts
end

Post.by_user(user).recent 

becomes

class Post < ActiveRecord::Base
  belongs_to :user
  named_scope :recent, {:limit => 10, :order => 'created_at desc'}
end

class User < ActiveRecord::Base
  has_many :posts
end

user.posts.recent 

One downside is that it’s no longer as easy to test the combined proxy_scope when using has_many with named_scope. I had a quick play with AssociationReflections but have yet to find a solution. For example – it would be nice to be able to do stuff like this:


user.posts.proxy_scope.should == {:conditions => {:user_id => 123 }}
user.posts.recent.proxy_scope.should == {:conditions => {:user_id => 123 }, :order => 'created_at desc', :limit => 10}
blog comments powered by Disqus