在一个has_many:through关系中,是否有一种简单的方法可以删除关联?
如果我有模型:
deal.rb
class Deal < ActiveRecord::Base
has_many :deal_events
has_many :events, :through => :deal_events
end
event.rb
class Event < ActiveRecord::Base
has_many :deal_events
has_many :deals, :through => :deal_events
end
deal_event.rb
class DealEvent < ActiveRecord::Base
belongs_to :deal
belongs_to :event
end
和在控制台中:
deal = Deal.first
event = Event.first
deal.events << event
我知道如果我想销毁deal和event的关联,我知道我可以调用
deal.events.destroy(event)
event.deals.destroy(deal)
但是deal.deal_events和event.deal_events仍然包含deal_event..是否有一种更干净的方法来做到这一点,并完全删除关系,让事件保留在event中。"全部"one_answers"全部"都留在"全部"里?由于
更新Rails控制台愚弄了我…
在我做了这个之后
deals.events << event
Rails没有输入查询,因为event.deal_events的查询已经执行了,所以这个…
1.9.3-p327 :020 > event.deal_events
=> []
正在发生,但是当我退出并再次进入rails控制台时,然后执行查询…
1.9.3-p327 :001 > event.deal_events
DealEvent Load (0.9ms) SELECT "deal_events".* FROM "deal_events" WHERE "deal_events"."event_id" = 1
=> [#<DealEvent id: 2, deal_id: 1, event_id: 1, created_at: "2013-01-15 21:37:24", updated_at: "2013-01-15 21:37:24">, #<DealEvent id: 3, deal_id: 1, event_id: 1, created_at: "2013-01-15 21:37:38", updated_at: "2013-01-15 21:37:38">]
我将标记@ChapleyWatson作为答案,因为它为我指明了正确的方向
在父模型
before_destroy :clear_my_association
# model stuff
private
def clear_my_association
self.my_association_model.clear
end