Tutorial :Why would association.build not assign parent_id to it child?



Question:

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.)


Solution:1

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  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »