[英]Rails get id of new record created in controller
I have jobplans
that have many jobtasks
. 我的工作jobplans
有很多工作jobtasks
。 These are like templates. 这些就像模板。 I want to create workorders
and tasks
from them. 我想从中创建工作workorders
和tasks
。
This is the code in the jobplans
controller: 这是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
My problem is the @workorder
is nil. 我的问题是@workorder
为nil。 I need each new task
to refer to the workorder
. 我需要每个新task
来引用task
workorder
。 How do access the id for the newly created workorder
? 如何访问新创建的工作单的workorder
?
Thanks for the help! 谢谢您的帮助!
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
You're never instantiating @workorder
(and you don't really need an instance variable). 您无需实例化@workorder
(并且您实际上不需要实例变量)。 Just change: 只是改变:
Workorder.create(wo_attrs)
to 至
workorder = Workorder.create(wo_attrs)
and further on 并进一步
jobtask_attrs.merge!({ workorder_id: workorder.id })
GL & HF GL和HF
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.