views:

166

answers:

2

So I have a User model that :has_many other models like Documents, Videos, Posts and the like. My question arises when I execute a "do" block from the User model like so:

has_many :posts do
    def recent
      find(:all, :order => 'created_at desc', :limit => 12)
    end
  end

This just lets me call something like user.posts.recent to find only those posts associated with the User. With this in place, how can I still add a :dependent => :destroy or :dependent => :delete_all to this association? Everything I have tried so far has errored out on me.

+3  A: 

It looks like you should take a look at using named_scope.

There's no reason why you should have a do block against your association.

You you should turn that recent method into a named scope and you can then tack on :dependent => destroy etc etc.

Good luck!

mwilliams
What I ended up doing was creating a recent_ method for all the models I needed this with and then moving the :dependent part in. Now the association is just that + the dependent and then I have something like:def recent_postsself.posts.find(:all, :order => "created_at DESC", :limit => 12end
Evan Lecklider
A: 

This should work just fine AFAIK:

has_many :posts, :dependent => :destroy do
    def recent
      find(:all, :order => 'created_at desc', :limit => 12)
    end
  end
Cameron Booth