Rails获取在控制器中创建的新记录的id

时间:2014-01-28 15:32:13

标签: ruby-on-rails

jobplans有很多jobtasks。这些就像模板。我想从中创建workorderstasks

这是jobplans控制器中的代码:

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

我的问题是@workorder是零。我需要每个新的task来引用workorder。如何访问新创建的workorder

的ID

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

这样做:

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

答案 1 :(得分:1)

你永远不会实例化@workorder(并且你真的不需要实例变量)。只需改变:

 Workorder.create(wo_attrs)

 workorder = Workorder.create(wo_attrs)

以及

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

GL& HF