我jobplans
有很多jobtasks
。这些就像模板。我想从中创建workorders
和tasks
。
这是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
?
感谢您的帮助!
答案 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