我有以下型號:如何使has_many_through關聯爲一個成員強制?
class City < ActiveRecord::Base
has_many :cities_regions_relationships
has_many :regions, through: :cities_regions_relationships
end
class Region < ActiveRecord::Base
has_many :cities_regions_relationships
has_many :cities, through: :cities_regions_relationships
end
class CitiesRegionsRelationship < ActiveRecord::Base
belongs_to :city
belongs_to :region
validates :city_id, presence: true
validates :region_id, presence: true
end
我想是讓它不可能創造一個城市沒有它連接到一個區域。然而,在嘗試之前,我必須能夠在尚未保存的城市建立關係。
我在控制檯嘗試這種(在已創建的區域)
c = City.new(name: "Test")
c.cities_region_relationship.build(region_id: Region.first.id)
c.save
然而,這種失敗,因爲關係不具有city_id(這是正常的,因爲我沒有救市尚未,它沒有ID)。
我可以嘗試其他方式,但我會一直有同樣的問題:如何創建一個新的對象的關係,尚未保存在數據庫中?
如果您對我最初的問題有其他完全不同的解決方案(強迫城市至少有一個地區),請不要猶豫,提出完全不同的建議。
「城市」可以有多個「地區」嗎? – AbM
@AbM是的。否則,我可以使用has_many和belongs_to,但不幸的是我的模型不是那麼簡單:( – Kaidjin
檢查此[SO帖子](http://stackoverflow.com/questions/950008/validate-at-least-one-in-has -and-belong-to-many) – AbM