在我的模型上,我有以下行:
has_many :notes, as: :notable, dependent: :destroy, after_add: :create_informal_note
当我创建与上面一行所在的模型关联的注释时,我希望触发create_informal_note
方法。
但是,该方法没有被解雇。
这里有什么问题?
潜在问题:
正在从note
的HTTP请求创建POST /api/v1/notes
。在请求正文的JSON中,它包含notable_id
和notable_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是否可以忽略关联,因此回调不会因此而触发?
答案 0 :(得分:1)
此回调仅在通过<<添加关联时有效。根据Mareq上面的评论和他提到的话题。
答案 1 :(得分:0)
可能值得向未来的读者指出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)