2012-06-10 41 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

相關問題