更新时如何删除has_many关系?

bru*_*zrk 1 ruby activerecord ruby-on-rails-4

我有两个表,例如:

table_one n x 1 table_two
Run Code Online (Sandbox Code Playgroud)

但是,table_two有许多table_one元素。

楷模:

class TableOne < ActiveRecord::Base
  belongs_to :table_two
end

class TableTwo < ActiveRecord::Base
  has_many :tables_one, class_name 'TableOne'
end
Run Code Online (Sandbox Code Playgroud)

我想table_onetable_two更新之前自动删除其中的所有元素(之前)

ps:或者,正确的位置在table_one.table_two.delete_all哪里?

更新1

该命令:

table_two = TableTwo.last
table_two.tables_one = [TableOne.new(<attributes>), TableOne.new(<attributes>, TableOne.new(<attributes>]
table_two.save
Run Code Online (Sandbox Code Playgroud)

应该删除table_two中所有现有的table_one,然后添加三个新的table_one。

ex0*_*0ns 5

我目前无法尝试,但我认为您想要:

class TableTwo < ActiveRecord::Base
  has_many :table_two, :dependent => :delete_all
end
Run Code Online (Sandbox Code Playgroud)

编辑添加依赖项标签以避免外键无效,而不是破坏记录来源:https : //www.ruby-forum.com/topic/4422973