Thursday 29 October 2009

Trick found in find(:all)

What happens if you want to search on an class but by an associated class - so I have a class of printers which are a type of organisation. Organisations have names, printers don't (or rather they do, but they have a name by virtue of being a type of organisation). How do I search on their name?

@printers = Printer.find(:all, :include=>:organisation,
:order=>"organisations.name",
:conditions=>['`organisations`.`name` like ?' , "%#{params[:search]}%"]).paginate( :page => params[:page], :order => 'name')


is how.
Couple of things to note - the :include calls in the associated class - and note the back-ticks (not single quotes) around the field - and also note that it is split in two.
Works like a dream.

No comments:

Post a Comment