Rails: Non id foreign key lookup ActiveRecord

旧街凉风 提交于 2019-11-30 03:02:51

I think you need to specify the primary key options on the associations as well:

class CoachClass < ActiveRecord::Base 
  belongs_to :coach, :foreign_key => 'user_name', :primary_key => 'user_name'
end

class Coach < ActiveRecord::Base
  has_many :coach_classes, :foreign_key => 'user_name', :primary_key => 'user_name'
end 

This specifies the method that returns the primary key of the associated object (defaulting to id).

There is a option called primary_key which is per default set to :id. You want to use:

has_many :coach_classes, :foreign_key => :user_name, :primary_key => :user_name

Also use these options on the belongs_to association.

Read more in the documentation.

You need to use finder_sql:

class Coach < ActiveRecord::Base
    has_many :coach_classes, :finder_sql => 'SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = "#{user_name}")'
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!