如何在Rails 4中设置自定义字符串外键?

时间:2013-07-22 12:28:28

标签: ruby-on-rails ruby foreign-keys associations ruby-on-rails-4

如何设置关联以使用string foreign_key正确设置has_one?

class Pharmaceutic < ActiveRecord::Base
  has_one :pharmaceutic_group, foreign_key: "code"
end

class PharmaceuticGroup < ActiveRecord::Base
  belongs_to :pharmaceutic, primary_key: 'code'
end

>> Pharmaceutic.last.pharmaceutic_group                                                                                        
  Pharmaceutic Load (0.3ms)  SELECT `pharmaceutics`.* FROM `pharmaceutics` ORDER BY `pharmaceutics`.`id` DESC LIMIT 1
  PharmaceuticGroup Load (0.3ms)  SELECT `pharmaceutic_groups`.* FROM `pharmaceutic_groups` WHERE `pharmaceutic_groups`.`code` = 2 ORDER BY `pharmaceutic_groups`.`id` ASC LIMIT 1
=> nil
>> Pharmaceutic
=> Pharmaceutic(id: integer, package_type: integer, group_code: string)
>> PharmaceuticGroup
=> PharmaceuticGroup(id: integer, code: string, name: string)

例如,当:Pharmaceutic有group_code:aaa而PharmaceuticGroup有代码:aaa我想得到Pharmaceutic.last.pharmaceutic_group.name => 'AAA group name'

1 个答案:

答案 0 :(得分:6)

我想您应该使用Pharmaceutic belongs_to :pharmaceutic_groupPharmaceuticGroup has_many :pharmaceutics,如下所示:

class Pharmaceutic < ActiveRecord::Base
  belongs_to :pharmaceutic_group, foreign_key: :group_code, primary_key: :code
end

class PharmaceuticGroup < ActiveRecord::Base
  has_many :pharmaceutics, foreign_key: :group_code, primary_key: :code
end