Reddirt
Reddirt

Reputation: 5953

Rails get id of new record created in controller

I have jobplans that have many jobtasks. These are like templates. I want to create workorders and tasks from them.

This is the code in the jobplans controller:

def copy_to_workorder
  @jobplan = Jobplan.find(params[:id]) # find original jobplan
  wo_attrs =  @jobplan.attributes
  wo_attrs.delete('woschedule_id')
  Workorder.create(wo_attrs)

  @jobplan.jobtasks.each do |jobtask|
    jobtask_attrs = jobtask.attributes
    jobtask_attrs.delete('jobplan_id')
    jobtask_attrs.merge!({ workorder_id: @workorder.id })
    Task.create(jobtask_attrs)
  end

  redirect_to @jobplan, notice: 'Project was successfully created.'
end

My problem is the @workorder is nil. I need each new task to refer to the workorder. How do access the id for the newly created workorder?

Thanks for the help!

Upvotes: 1

Views: 2363

Answers (2)

Agis
Agis

Reputation: 33626

Do this:

def copy_to_workorder
  @jobplan = Jobplan.find(params[:id]) # find original jobplan
  wo_attrs =  @jobplan.attributes
  wo_attrs.delete('woschedule_id')
  workorder = Workorder.create(wo_attrs)
  # ^^^^^ saving the newly created record in a local variable
  #       so we can refer to it later

  @jobplan.jobtasks.each do |jobtask|
    jobtask_attrs = jobtask.attributes
    jobtask_attrs.delete('jobplan_id')
    jobtask_attrs.merge!(workorder_id: workorder.id)
    #                                  ^^^^^^ now fetch its id
    Task.create(jobtask_attrs)
  end

  redirect_to @jobplan, notice: 'Project was successfully created.'
end

Upvotes: 4

rlecaro2
rlecaro2

Reputation: 755

You're never instantiating @workorder (and you don't really need an instance variable). Just change:

 Workorder.create(wo_attrs)

to

 workorder = Workorder.create(wo_attrs)

and further on

jobtask_attrs.merge!({ workorder_id: workorder.id })

GL & HF

Upvotes: 1

Related Questions