This seems like it should have been asked numerous times already, but my
Google-fu isn't strong enough to find the answer. DHH advocates
separating HABTM relationships into a join model, and I need to store
some metadata about the join, so this makes sense. The problem is
creation order and validations.
Say, you have three models, like so:
class Foo < AR::Base
has_many :bars, :through => :quux
class Bar < AR::Base
has_many :quuxes, :dependent => :destroy
has_many :foos, :through => :quuxes
class Quux < AR::Base
Foo is valid without any Bars, and a Bar may belong to multiple Foos.
However, a Bar should never exist without being associated with at least
So, how would you ensure that every time a Bar is created, the proper
Quux is also created, without ever leaving an opportunity for a Bar to
exist without a Foo?
My initial thought is that a transaction is necessary, in this order:
1) Create Bar (rollback on fail)
2) Create Quux, referencing bar.id and foo.id (rollback on fail)
How do I enforce this order and maintain database integrity in the model
This seems silly; if there's an obvious answer/resource I'm missing,
please let me know. Thanks.