【问题标题】:Rails: Non id foreign key lookup ActiveRecordRails:非 id 外键查找 ActiveRecord
【发布时间】:2010-07-23 11:20:38
【问题描述】:

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

class CoachClass < ActiveRecord::Base
  belongs_to :coach
end

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

当我做一个 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_classes 表中有coach_id。

【问题讨论】:

  • 不请自来的建议:您可能需要考虑在表中添加一个coach_id,如果这种关系变得嵌套和更常规,它会更容易。
  • 谢谢杰德。但出于某种原因,我不想让 coach_id 出现。

标签: ruby-on-rails activerecord foreign-key-relationship has-many belongs-to


【解决方案1】:

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

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)。

【讨论】:

  • 约翰,你确定协会的另一边在这里有影响吗?可以简单地拥有has_many,而另一侧没有belongs_to。
【解决方案2】:

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

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

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

在documentation 中了解更多信息。

【讨论】:

    【解决方案3】:

    你需要使用finder_sql:

    class Coach < ActiveRecord::Base
        has_many :coach_classes, :finder_sql => 'SELECT * FROM `coach_classes` WHERE (`coach_classes`.user_name = "#{user_name}")'
    end
    

    【讨论】:

    • 注意——他们在以后的版本中去掉了这个。当他们的“魔法”没有您需要的功能时,它真的是救命稻草。
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2012-06-25
    • 2013-07-28
    • 1970-01-01
    相关资源
    最近更新 更多