本文介绍了如何在Rails 4中设置自定义字符串外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用字符串foreign_key正确设置关联has_one?
How to set up associations to set up properly has_one using string foreign_key?
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 has group_code : aaa 和PharmaceuticGroup有代码: aaa 我想得到 Pharmaceutic.last.pharmaceutic_group .name => 'AAA group name'
For example when: Pharmaceutic has group_code: aaa and PharmaceuticGroup has code: aaa I would like to get Pharmaceutic.last.pharmaceutic_group.name => 'AAA group name'
推荐答案
我猜你应该使用 Pharmaceutic belongs_to:pharmaceutic_group 和 PharmaceuticGroup has_many:pharmaceutics ,像这样:
I guess you should rather use Pharmaceutic belongs_to :pharmaceutic_group and PharmaceuticGroup has_many :pharmaceutics, like this:
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
这篇关于如何在Rails 4中设置自定义字符串外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!