【问题标题】:Rails update author_id in books table after deleting and creating a new author record删除并创建新的作者记录后,Rails 更新 book 表中的 author_id
【发布时间】: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: &lt;author_id&gt;) 没有?
  • @SebastianPalma 但是如果还有其他具有不同 author_id 的书呢?
  • 您可以将它们分组。不清楚你想做什么。你能进一步解释一下吗?
  • @SebastianPalma 是的,当然。更新了问题
  • 删除author1后,author1的书籍也被销毁了。

标签: ruby-on-rails ruby activerecord associations


【解决方案1】:

我建议你先创建第二作者。如果您先删除第一作者,您将无法获取与第一作者关联的书籍。

寻找新作者

new_author = Author.find(new_id)

把旧书换成新书

old_author = Author.find(old_id)
old_author.books.update_all(author_id: new_author.id)

删除旧作者

old_author.destroy

这将确保不会丢失任何数据,也不会出现孤立数据。

【讨论】:

  • 请注意update_all 不会运行回调。相反,您可以执行author_1.books.each { |book| book.update_attributes(author_id: author_2.id) } 之类的操作。
【解决方案2】:

听起来您希望在删除作者后保留图书对象,以便您可以将其分配给其他作者。如果是这种情况,您可能需要考虑使用拥有和属于多个关系:https://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association。所以你会有 3 个表:authorsbooksauthors_booksauthor_books 将只有 2 列:author_idbook_id

另一种选择是像这样更改Author

  class Author < ApplicationRecord
    has_many :books, dependent: :nullify
  end

现在,当删除作者时,书籍不会被删除,而是在 books 表中将 author_id 设置为 null,以显示以前属于特定作者的所有书籍:https://guides.rubyonrails.org/association_basics.html#dependent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多