views:

129

answers:

1

I've got the following models:

In plan.rb

has_many :tickets

and in ticket.rb

belongs_to :plan
validates_presence_of :plan_id

When executing the following code in the controller

@plan.tickets.build( ... )
@plan.save

save fails with error_message for ticket: plan can't be blank. (plan is valid.)

+2  A: 

I've had this happen when my object was new and unsaved when I called build on it.

build assigns the plan_id, and if @plan's id is nil, then your ticket's plan_id will be nil. Because build doesn't validate or save, you don't find out until later.

Other methods of adding an associated object to an unsaved object seem to remember that it's unsaved and set the id appropriately. So try this:

 @plan.tickets << Ticket.new(...)
 @plan.save
Sarah Mei