删除has_many的关联:通过

时间:2013-01-15 18:15:10

标签: ruby-on-rails-3

在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.events.destroy(event)
event.deals.destroy(deal)

但是deal.deal_events和event.deal_events仍然包含deal_event ..是否有更简洁的方法来完成此操作并完全删除关系并让事件保留在Event.all中并且交易仍在Deal.all中?感谢

更新

Rails控制台欺骗了我..

我做完之后

deals.events << event

Rails没有输入查询,因为event.deal_events的查询已经执行了所以这个..

1.9.3-p327 :020 > event.deal_events
 => [] 

正在发生,但当我退出并再次进入rails console时,则执行查询..

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标记为答案,因为它指出了我正确的方向

1 个答案:

答案 0 :(得分:0)

在您的父模型

before_destroy :clear_my_association


# model stuff

private

  def clear_my_association

    self.my_association_model.clear

  end