I have a model “Conversation” and a model “Leader”. A Conversation is always led by exactly 1 Leader.
I’ve overridden Conversation’s “validate” method to validate the presence of an associated Leader model.
If I add a similar validation to the Leader model, however, Conversations can no longer be saved on creation because the Leader model is invalid.
On creation of both a new Conversation and new Leader how can I validate in each model that it is associated with the other? Is there a best practice? The closest I’ve come is to override Leader’s “validate_on_update” method to ensure the presence of a Conversation but that still allows new Leader objects to be created without a Conversation, filling my tables with junk.
That way you can't save a conversation without assigning it a leader,
but the leader doesn't have to be saved yet.
Well, that’s where I’m at right now. I’d like to be in a situation where Conversation validates that it has a Leader and Leader validates it has a Conversation before either is saved.
Don’t overdo your requirements. Take your requirements lightly.
From what I can see in your example, Leader plays a larger role in your domain, so it has priority over the Conversation.
I would model Leader having zero or more (0…*) Conversations, Conversation having 1 Leader. A simple one to many relationship between those domain objects.
As from what I can tell, your are trying to create both at the same time in the view, thus sending both objects over to the controller.
While creating a Conversation, you could give the user the opportunity to create a Leader, if its currently not available, or he wants to get a new one. You could use AJAX to access the create action in the leader controller having it available prior to saving the Conversation.
That way you can't save a conversation without assigning it a leader,
but the leader doesn't have to be saved yet.
Well, that�s where I�m at right now. I�d like to be in a situation where
Conversation validates that it has a Leader and Leader validates it has
a Conversation before either is saved.
Just validate that there are keys: Conversation validates_presence_of
:leader, Leader validates_presence_of :conversation (perhaps). Do the
rest with foreign key constraints in the DB. As you've discovered, the
application layer is the wrong place for this sort of simple integrity
check.
--
You received this message because you are subscribed to the Google
Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.