2012-06-10 56 views
2

如果我有一个名为'templates'的字段'a,b,c,d,e,f,g'的模型,并且我有一个“报告”模型具有独特的领域,但也与'模板'具有相同的字段:'蓝色,红色,金色,绿色,a,b,c,d,e,f,g')将字段从一个模型复制到包含相同字段的另一个模型

说新形式Report,有一个下拉列表来选择一个模板,这个列表的值将是一个模板ID,因此,在Reports的创建操作中,我创建了一个新的Report对象,然后通过id找到所选模板

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

此时(考虑到@report对象包含所有字段t他@template对象),是否有一种将@template的值复制到@report对象的consise方法?

谢谢! 的Rails 2.3.5/1.8.7的Ruby

回答

3

最简单的方法:

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

哈 - 谢谢。我以前从来没有想过,但在“创建”操作上,Rails非常聪明,不会发送带有insert语句的'id'字段。虽然当你做一个“.save”的时候,Rails正在看什么,以确定它不应该通过插入id来传递id。 – Reno

+1

还要考虑到要复制的字段只是您的'''attr_accesible''语句中定义的字段。 – Cacofonix

相关问题