【发布时间】:2019-09-25 06:27:41
【问题描述】:
这是Author 模型和Book 模型
class Author < ApplicationRecord
has_many :books, dependent: :destroy
end
class Book < ApplicationRecord
belongs_to :author
end
我创建了 2 个作者(作者 1 和作者 2)并为每个作者添加了 2 本书。
之后我删除了 author1 并创建了一个新作者(author3)。现在,我想把 author1 的两本书送给 author3。
是否有 ActiveRecord 方法可以用新作者更新书籍 author_id?
【问题讨论】:
-
books.update_all(author_id: <author_id>)没有? -
@SebastianPalma 但是如果还有其他具有不同 author_id 的书呢?
-
您可以将它们分组。不清楚你想做什么。你能进一步解释一下吗?
-
@SebastianPalma 是的,当然。更新了问题
-
删除
author1后,author1的书籍也被销毁了。
标签: ruby-on-rails ruby activerecord associations