与同一模型相关联

问题描述 投票:-1回答:1

我有一个City模型,我想与另一个被称为姐妹城市的城市建立一个可选择的关系。为了避免向cities添加另一列,我想创建一个包含关联的连接表。

create_table :sister_city_mappings do |t|
  t.integer :city_id
  t.integer :sister_city_id

  t.timestamps null: false
end

class City
  has_one :sister_city_mapping, :class_name => 'SisterCityMapping', 
  foreign_key: :city_id
  has_one :sister_city, :class_name => 'City', through: 
  :sister_city_mapping, source: :sister_city
end

class SisterCityMapping
  belongs_to :city, :class_name => 'City'
  belongs_to :sister_city, :class_name => 'City',
  foreign_key: :sister_city_id
end

这种作品,因为我可以做City.first.sister_city = City.last但我无法通过形式参数处理这种关系,就像我想的那样干净:

City.first.sister_city_id = 2
NoMethodError: undefined method `sister_city_id=' for #<City:0x007f893be1b178>

并尝试:

City.first.sister_city = 2
ActiveRecord::AssociationTypeMismatch: City(#70113697769780) expected, got Fixnum(#70113638622260)

我认为这种关联很可能不正确,我也尝试过SisterCityMapping has_one :sister_city,但没有成功。

ruby-on-rails activerecord
1个回答
0
投票

你真的应该只在你的cities表中添加一个sister_city_id列:

class City
  has_one :sister_city, :class_name => 'City'
end

如果您确实想使用此连接表关联,则可以创建如下关系:

City.first.sister_city = City.find(2)

© www.soinside.com 2019 - 2024. All rights reserved.