我有两个不同的对象,它们可以属于一个父对象。这些子对象也可以彼此属于(多对多)。确保属于彼此的子对象也属于同一个父对象的最佳方法是什么。
作为我正在尝试做的一个例子,我有一个Kingdom同时具有许多People和Land. 该People模型将有一个自定义validate检查每个相关的Land和 error.adds 是否有一个不匹配的kingdom_id. 该Land模型将具有类似的validate.
这似乎有效,但是在更新它时允许记录保存'THIS IS AN ERROR'错误people.errors,但是Land引发错误的记录已添加到People集合中。
kingdom = Kingdom.create
people = People.create(:kingdom => kingdom)
land = Land.create(:kingdom_id => 999)
people.lands << land
people.save
puts people.errors.inspect # @messages={:base=>["THIS IS AN ERROR"]
puts people.lands.inspect # [#<Land id: 1...
理想情况下,我希望错误取消记录更新。我应该采取另一种方式来解决这个问题,还是我完全走错了方向?
# Models:
class Kingdom < ActiveRecord::Base
has_many :people
has_many :lands
end
class People < ActiveRecord::Base
belongs_to :kingdom
has_and_belongs_to_many :lands
validates :kingdom_id, :presence => true
validates :kingdom, :associated => true
validate :same_kingdom?
private
def same_kingdom?
if self.lands.any?
errors.add(:base, 'THIS IS AN ERROR') unless kingdom_match
end
end
def kingdom_match
self.lands.each do |l|
if l.kingdom_id != self.kingdom_id
return false
end
end
end
end
class Land < ActiveRecord::Base
belongs_to :kingdom
has_and_belongs_to_many :people
end