Rails: How to observe join records that don't actually have a Model?
-
29-08-2019 - |
Question
Is it possible, using an Observer, to observe the creation of JOIN records? For example, you have a User Model that has_and_belongs_to_many Book Models. Is it possible to monitor books_users records as they are created or deleted or must I have a BookUser model to do this?
Example of what I want to observe:
User.books << book
OR
User.books.push(book)
OR whatever!
Thanks,
Dave K.
Solution
This is the exact reason you should be using a has_many :through, instead of has_and_belongs_to; It allows you to create a BookUser model in which regular activerecord callbacks/observers can be used (such as after_save). This site explains the differences better, http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow