can associations take arguments?

Let's say an Author has many books. Can I say stuff like: author = Author.find :first author.books :order_by => 'publication_date' or author.books :condition => ['publication_data > ?', somedate]

Thanks for the help.

Like this:

author.books.find :all, :order => 'publication_date' author.books.find :all, :conditions => [ 'publication_date > ?', somedate]

Simon

Christopher J. Bottaro wrote:

You can also use association extensions

class Author < AR::Base   has_many :books do     def published_on(d)       find(:all, :conditions => ["published_on = ?", d])     end

    def published_before(d)       find(:all, :conditions => ["published_on < ?", d])     end

    def published_after(d)       find(:all, :conditions => ["published_on > ?", d])     end   end end

author.books.published_on(some_date) etc...

keep in mind this only adds those methods to the association, not to the model itself.

Chris

Awesome, that is what I was looking. I knew Rails could do it, I just couldn't find the syntax. Thank you.

Next question... how smart/efficient is Rails about doing that query? Is the order and condition done in Ruby code or in SQL?

Thanks, -- Christopher

Christopher,

You can easily check the sql produced by running a tail -f against your development.log.

You also should read up on some of Jamis' great recent posts:

http://weblog.jamisbuck.org/2007/1/9/extending-activerecord-associations http://weblog.jamisbuck.org/2007/1/18/activerecord-association-scoping-pitfalls

author.books.find(:all, :order => 'publication_date)

and

author.books.find(:all, :conditions => ['publication_data > ?', somedate])