Why doesn't connection.build assign parent_id to this child?

I have 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 with error error_message for the ticket: the plan cannot be empty. (the plan is valid.)

+3
source share
1 answer

It happened to me when my object was new and unsaved, when I typed build.

buildassigns plan_id, and if @planid is zero, then your ticket plan_idwill be zero. Since it builddoes not check and does not save, you will not recognize it later.

, , , . :

 @plan.tickets << Ticket.new(...)
 @plan.save
+3

Source: https://habr.com/ru/post/1706764/


All Articles