Require a model to have another model? Basically, a model validation
What I mean is, is it possible in Rails to require at least one instance of a model in a relationship?
For example, in my discussion.rb
I have:
has_many :posts
And in my post.rb
:
belongs_to :discussion
How can I make it that in order to create a discussion you need to have at least one Post? I was not sure how to search for 开发者_StackOverflowthis question, so I apologize if it's already been asked.
validates_presence_of will do the trick I think.
The post record will need a discussion_id foreign key in order to be associated with a discussion. The discussion can't be created (and given an id) until the post is created. It's a catch-22.
You'll have to introduce something else, like a "complete" boolean on the discussion model that only gets flipped true after a post is created.
精彩评论