26

我想ActiveRecord通过表中的非 id 列进行查找。希望当我给你我的代码示例时这一点很清楚。

class CoachClass < ActiveRecord::Base
  belongs_to :coach
end

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

当我做 a coach_obj.coach_classes时,这会正确触发

SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 2)

(2 是那个教练在id这里,这是我的问题。)

我想让它触发

SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = 'David')

(“大卫”是那个教练的user_name

user_name是独一无二的,并且出现在两个表中。

出于某种原因,我不想coach_id在我的桌子上放一个。coach_classes

4

3 回答 3

53

我认为您还需要在关联上指定主键选项:

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 

这指定了返回关联对象的主键的方法(默认为id)。

于 2010-07-23T11:27:56.593 回答
10

有一个名为的选项primary_key默认设置为:id. 你想使用:

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

belongs_to也可以在关联上使用这些选项。

在文档中阅读更多内容。

于 2010-07-23T11:31:43.057 回答
-4

您需要使用finder_sql

class Coach < ActiveRecord::Base
    has_many :coach_classes, :finder_sql => 'SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = "#{user_name}")'
end
于 2010-07-23T11:28:36.500 回答