views:

170

answers:

2

I have a rails query like:

     @user = User.find_by_username(params[:search], :include => [:user_similars])    

Models: user (has_many :user_similars), user_similar (belongs_to :user)

The user_similars mysql table has a "user_id" field as a foreign key, but I don't want :include to join on that for this instance. I'd like to join on another field called "user_id_similar"

Is there a parameter to change the way :include behaves so it can join on another field?

Or should I be using :join with a different option?

Or maybe edit the model method declarations?

Thanks!

+1  A: 

When you define the relationship between the two tables, you can specify which column to use as the Foreign Key. In this case, set "user_id_similar" to be the FK, and include should then use that when performing the join.

Toby Hede
Cool. Thanks!I was putting it in the wrong model.
bandhunt
+2  A: 

Thanks Toby! In the user model user I added:

has_many :user_similars, :foreign_key => "user_id_similar"

and this solved it.

bandhunt
If I'm not mistaken you need to specify the foreign key in both models for the links to work in both directions.
Mike Sutton