gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:28:52 26 4
gpt4 key购买 nike

如何设置关联以使用字符串 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组名'

最佳答案

我猜你应该使用 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

关于ruby-on-rails - 如何在 Rails 4 中设置自定义字符串外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com