我有两个用脚手架生成的模型,Template和Article
Template has_many :articles和Article belong_to :template
Template以title:string body:text作为字段。Article以title:string body:text template_id:integer作为字段。
问题是:当创建一个新的字段时,如何使用Template模型预先填充Article的字段?
发布于 2015-06-10 01:46:21
您可以将逻辑放入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回调中。
希望这能有所帮助!
编辑: 链接到回调指南
https://stackoverflow.com/questions/30745667
复制相似问题