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.
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
likly. have you tried?
On Jan 26, 2:40 pm, Simon P. [email protected] 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
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
On 1/26/07, Christopher J. Bottaro [email protected] 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
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs