문제

Suppose I have an Comment model that belongs_to a Post model.

I want to make it so that creation of a new Comment instance (whether by new, create, find_or_create_by_x, etc.) will fail (preferably raise an exception) unless the Post is set immediately (either by passing it in as a parameter or by always referencing the post when creating a comment, e.g. post.comments.new or post.comments.create).

I want to do this because I want to set some default values in the comment object which are based on the post...so the post reference needs to be immediately valid.

What is the best way to accomplish this? Thanks.

도움이 되었습니까?

해결책

I think in order for this to work with new you have to do it in after_initialize:

def after_initialize
  raise "no Post" unless post
end

Seems like overkill though, since that has to run every time a Comment is instantiated. I'd say write tests that ensure the defaults are being set appropriately.

다른 팁

I would add a validation in your Comment model like so:

class Comment < ActiveRecord::Base
  validates_presence_of :post_id
end

Then create new comments using:

@post = Post.find(params[:post_id])

@post.comments.create(params[:comment])
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top