【问题标题】:How to identify newly added has_many association in rails after_commit如何在rails after_commit中识别新添加的has_many关联
【发布时间】:2020-07-29 16:12:33
【问题描述】:

author 类中有以下关联

has_many :books,
class_name :"Learning::Books",
through: :elearning,
dependent: :destroy

将 after_commit 作为,

after_commit :any_book_added?, on: :update

def any_book_added?
     book = books.select { |book| book.previous_changes.key?('id') }
     # book's previous_changes is always empty hash even when newly added
end

无法找到与此方法新添加的关联。这是因为class_name吗?

【问题讨论】:

  • 您是否考虑过翻转这个逻辑并在book.rb 上添加after_commit 以告诉拥有bookauthor 添加了一本新书?
  • after_addhas_many: guides.rubyonrails.org/…
  • 是的@yez。但我在作者模型中需要它以及其他关联更改.. JoshBrody 当我在关联中有 where 子句时它不起作用

标签: ruby-on-rails ruby associations


【解决方案1】:

Rails 有 a couple methods that might help you, before_add and after_add

使用这个,你可以定义一个方法来设置一个实例变量为true

class Author < ApplicationRecord
  has_many :books, through: :elearning, after_add: :new_book_added

  def any_book_added?
    @new_book_added 
  end

  private

  def new_book_added
    @new_book_added = true
  end
end

然后,当您向作者添加一本书时,将调用 new_book_added 方法,您可以在以后的任何时间询问您的 Author 类是否为 any_book_added?

author = Author.last
author.any_book_added?
=> false
author.books = [Book.new]
author.any_book_added?
=> true

如您所见,回调方法new_book_added 也可以接受已添加的图书,因此您可以保存该信息。

【讨论】:

  • @josh-brody 在上面的评论中指出了这一点,我只是对其进行了扩展。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 2014-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多