Patrick A. wrote:
I’m using a simple search function. It’s working
great except for foreign keys.
I have one table pets (id,name,owner_id)
and another table people(id,name)
owner_id being a foreign key of pet pointing to people name.
here it is on the pet controller:
@paginator, @pets= paginate(:pets, :conditions =>[“name OR owner_id
like ?”,"%"+params[:filter]+"%"], :include =>person,:order_by =>
@sort_by,:per_page => default_per_page )
it searches great in name but not in owner_id. I mean it searches
people id instead of the person name it’s referring. Any idea how to
make it search through the foreign key?
The convention in Rails is to name your foreign key after the class of
the associated model, not the role it plays. You can tell Rails the
class of the model with :class_name, and to use a different key with the
:foreign_key option on the association message. You have to say both
because the :class_name option sets the foreign key, so you have to
override that explicitly.
belongs_to :owner, :class_name => “Person”, :foreign_key => owner_id
If you already have your association set up that way, then maybe your
search code isn’t doing the right thing to find the foreign key.
Person.reflect_on_association(:owner) returns a reflection object that
includes information about the association name, associated class,
foreign key, etc. - that should be where you look to find the correct