Rails 模型的回调并不总是从另一个模型触发
我有一个奇怪的问题。例如,我只有两个模型:
class Book < ActiveRecord::Base
belongs_to :shelf
after_update :specific_callback
private
def specific_callback
# some actions here
end
end
class Shelf < ActiveRecord::Base
has_many :books
end
所以问题是,如果我通过书改变确切的书架关系 - 例如:
book.shelf = shelf
# or
book.shelf_id = shelf.id
然后如果我保存书 - 没关系,所以回调正常触发,但如果我通过 < 处理书strong>shelf 及其方法 book_ids 就会出现问题,例如:
shelf.book_ids = [1,2,3]
这里书籍的回调仅在新添加的书籍上触发,换句话说,如果 book.shelf_id strong> 从 nil 更改为某些 shelf.id - 没关系,回调会正常触发,但如果 book.shelf_id 从某些内容更改为 nil - 不会触发回调。
当所有书籍的架子 ID 更改时,我在控制台中看到所有查询,但对于那些架子 ID 为 nil 的人不会触发回调。
我已经尝试过使用after_update、after_save。我什至尝试使用观察者,但问题仍然出现。
I've got a strange problem. For example i have only two models:
class Book < ActiveRecord::Base
belongs_to :shelf
after_update :specific_callback
private
def specific_callback
# some actions here
end
end
class Shelf < ActiveRecord::Base
has_many :books
end
So the problem is that if i change exact book-shelf relation through book - for example:
book.shelf = shelf
# or
book.shelf_id = shelf.id
and then if i save book - its okay, so callback fires normally, but if i work with book through shelf and with its method book_ids there problems start, for example:
shelf.book_ids = [1,2,3]
here callbacks for books are only firing on newly added books, in other words if book.shelf_id changes from nil to some shelf.id - it's okay, and callback fires normally, but if book.shelf_id changes to nil from something - there is no firing of callback.
I see all queries in console when shelf_id changes for all books, but callbacks not firing for those who get nil for shelf_id.
Ive already tried to use after_update, after_save. Ive even tried to use observers, but the problem stills appears.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论