2015-06-10 26 views
0

例如我有支架產生的兩種型號,TemplateArticlerails 4商品數據模板

Template has_many :articlesArticle belong_to :template

Templatetitle:string body:text的領域。 Articletitle:string body:text template_id:integer作爲字段。

現在的問題是:如何創建一個新的時候,使用Template模型預先填充Article的字段?

+0

是你想要的型號有重複的數據? – daslicious

+0

一個模型是另一個模型的基礎,或許更好的例子是基於模板而不是文章創建字母。 – mguz

回答

1

你可以把邏輯在before_create回調

class Article < ActiveRecord::Base 
    belongs_to :template 

    before_create :assign_attributes_from_template 


    def assign_attributes_from_template 
    title = template.title 
    # etc 
    end 
end 

這之後審定會跑不過,所以如果你需要驗證這些字段你應該把這個在before_validation, on: :create回調來代替。

希望這會有所幫助!

編輯:Link to callbacks指南

+1

你指的是[hooks](http://en.wikipedia.org/wiki/Hooking),但我想你的意思是[callbacks](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) – daslicious

+0

哦耶。抱歉。我今天早上在喝咖啡之前寫了這篇文章。其實我的意思是回調。將更新我的答案。謝謝 – RustComet

+0

謝謝!我會嘗試 – mguz