繁体   English   中英

Rails after_add 关联回调未触发

[英]Rails after_add association callback not triggering

在我的模型上,我包含以下行:

has_many :notes, as: :notable, dependent: :destroy, after_add: :create_informal_note

当我创建一个与上面一行所在的模型相关联的注释时,我希望create_informal_note方法被触发。

但是,该方法并未被触发。

这里有什么问题?

潜在问题:

note是从 HTTP 请求到POST /api/v1/notes 在请求正文的 JSON 中,它包括notable_idnotable_type 它正在设置实际字段,而不是将notable设置为对象。

POST /api/v1/notes

{
  "note": {
    "text": "Test note",
    "notable_id": 1,
    "notable_type": "AnotherModel"
  }
}

以及我正在运行的 Rails Web 服务器的输出日志:

Processing by NotesController#create as JSON
  Parameters: {"note"=>{"notable_id"=>"1", "notable_type"=>"AnotherModel", "text"=>"Test note", "email"=>1, "documents_attributes"=>nil}}
   (0.2ms)  BEGIN
  SQL (2.0ms)  INSERT INTO `notes` (`text`, `notable_id`, `notable_type`, `created_at`, `updated_at`) VALUES ('Test note', 1, 'AnotherModel', '2016-02-19 11:32:56.401216', '2016-02-19 11:32:56.401216')
   (1.1ms)  COMMIT

Rails 是否会忽略关联,因此不会触发回调?

此回调仅在根据上面 Mareq 的评论和他提到的线程通过 << 添加关联时才有效。

可能值得向未来的读者指出此功能记录在 Active Record 文档中: https : //guides.rubyonrails.org/association_basics.html#association-callbacks

# These callbacks are called only when the associated objects 
# are added or removed through the association collection:


# Triggers `before_add` callback
author.books << book
author.books = [book, book2]

# Does not trigger the `before_add` callback
book.update(author_id: 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM