【问题标题】:Rails One-One Relationship- Foreign Key LocationRails 一对一关系 - 外键位置
【发布时间】:2010-11-15 19:47:39
【问题描述】:

我有两个模型,地址和国家。地址包含基本地址信息(line1、line2、city 等),并且与国家/地区具有一对一的关系。

国家表是只读的,我不希望它改变。

我的表单在“地址”表中创建了一个 country_id 列,但它正在国家表中寻找 address_id

如何告诉 rails 使用地址表中的 country_id 来查找国家/地区?

模型如下所示:

class Address < ActiveRecord::Base
   belongs_to :consultant
   has_one :country
   accepts_nested_attributes_for :country   
end

class Country < ActiveRecord::Base
   belongs_to :address
end

谢谢!

【问题讨论】:

    标签: mysql ruby-on-rails activerecord ruby-on-rails-3


    【解决方案1】:

    来自belongs_to 文档:

    仅当此类包含外键时才应使用此方法。

    所以你的代码应该是:

    class Address < ActiveRecord::Base
      has_to :consultant
      belongs_to :country
      accepts_nested_attributes_for :country   
    end
    
    class Country < ActiveRecord::Base
      has_one :address
    end
    

    【讨论】:

    • 谢谢!我还必须将 ":primary_key => :country_id" 添加到 Address 以使其正常工作。
    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-19
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多