Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to observe join records that don't actually have a Model?

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.

like image 393
David Avatar asked Oct 14 '22 17:10

David


1 Answers

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

like image 176
capotej Avatar answered Oct 18 '22 15:10

capotej