has_and_belongs_to_many和accepts_nested_attributes_for

时间:2013-01-30 17:02:24

标签: ruby-on-rails ruby-on-rails-3 has-and-belongs-to-many

class Trip
  has_many   :trip_places
  has_many   :places, through: :trip_places

  accepts_nested_attributes_for :places
end

class Place
  has_many :trip_places
  has_many :trips, through: :trip_places

  validates :name, uniqueness: true
end

class TripPlace
  belongs_to :trip
  belongs_to :place
end

所以我们通过旅行地点有很多地方旅行,并接受地方的嵌套属性。地方名称也必须是唯一的。

我想拥有以下功能,但无法找到优雅的解决方案:

假设我们创建了一个旅程T,其中有两个地方P1 = 'hawaii'P2 = 'costa rica'

如果我修改行程,并将hawaii更改为bora bora,则会修改Place

问题在于我想创建一个名为bora bora的新地点,并修改TripPlace模型以使用新版本更新place_id

同样的事情就是破坏,如果我在表单中销毁place,我只想删除TripPlace中的引用,而不是实际的Place

当然,创建功能应该是相似的,如果该地方存在,只需创建TripPlace参考。

现在,我不认为accepts_nested_attributes_for真的有帮助,但是想不出一个好的解决方案

0 个答案:

没有答案