Mysql Rails一对一关系-外键位置

Mysql Rails一对一关系-外键位置,mysql,ruby-on-rails,activerecord,ruby-on-rails-3,Mysql,Ruby On Rails,Activerecord,Ruby On Rails 3,我有两种型号,地址和国家。地址包含基本地址信息(第1行、第2行、城市等),并与国家/地区有一对一的关系 国家表是只读的,我不想更改 我的表单在“addresses”表中创建了一个country\u id列,但它在country表中查找address\u id 如何告诉rails使用addresses表中的country_id查找国家 以下是模型的外观: class Address < ActiveRecord::Base belongs_to :consultant has_o

我有两种型号,地址和国家。地址包含基本地址信息(第1行、第2行、城市等),并与国家/地区有一对一的关系

国家表是只读的,我不想更改

我的表单在“addresses”表中创建了一个country\u id列,但它在country表中查找address\u id

如何告诉rails使用addresses表中的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
类地址
谢谢

来自文档:

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

因此,您的代码应该是:

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

class Country < ActiveRecord::Base
  has_one :address
end
类地址
来自文档:

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

因此,您的代码应该是:

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\u key=>:country\u id”才能使其正常工作。谢谢!我还必须在地址中添加“:primary\u key=>:country\u id”才能让它正常工作。