将字段从一个模型复制到包含相同字段的另一个模型

时间:2012-06-10 02:24:50

标签: ruby-on-rails

如果我有一个名为'模板的模型'字段' a,b,c,d,e,f,g'我有一个"报告'具有唯一字段的模型,但也包含与“模板”相同的字段。有:'蓝色,红色,金色,绿色,a,b,c,d,e,f,g')。

在新报告的表单上说,有一个用于选择模板的下拉列表,该列表的值将是模板ID。因此,在Reports的创建操作中,我创建一个新的Report对象,然后按id找到所选的模板。

@report = Report.new(params[:report])
@template = find(params[:report][:template_id])

此时(考虑到@report对象包含@template对象所做的所有字段),是否有将@template的值复制到@report对象的简单方法?

谢谢! Rails 2.3.5 / Ruby 1.8.7

1 个答案:

答案 0 :(得分:3)

最简单的方法:

@report = Report.new(params[:report])
@template = find(params[:report][:template_id])
@template.attributes = @report.attributes #this copies fields from report to template