Can associations take arguments?


#1

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.


#2

Like this:

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

Simon


#3

likly. have you tried?


#4

On Jan 26, 2:40 pm, Simon P. removed_email_address@domain.invalid wrote:

Like this:

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

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


#5

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


#6

On 1/26/07, Christopher J. Bottaro removed_email_address@domain.invalid wrote:

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


Zack C.
http://depixelate.com


#7

On Jan 26, 2007, at 21:10 , Christopher J. Bottaro wrote:

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]

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

and

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


Jakob S. - http://mentalized.net