开发者

Ruby on Rails: joining two tables on something other than the standard foreign key

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!


Thanks Toby! In the user model user I added:

has_many :user_similars, :foreign_key => "user_id_similar"

and this solved it.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜