views:

23

answers:

2

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.

A: 

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.

zetetic
I don't mind the overhead which it seems like would come with the territory.
Ken Thompson
A: 

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])
Beerlington
That prevents saving without a post_id, not instantiating without one.
Ken Thompson