开发者

Require a model to have another model? Basically, a model validation

开发者 https://www.devze.com 2023-03-11 17:02 出处:网络
What I mean is, is it possible in Rails to require at least one instance of a model in a relationship?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消