rails 4篇文章数据模板

rails 4 article data template

例如我有两个用脚手架生成的模型,TemplateArticle

Template has_many :articlesArticle belong_to :template

Templatetitle:string body:text 作为字段。 Articletitle:string body:text template_id:integer 作为字段。

问题是:当创建一个新字段时,我如何使用 Template 模型预填充 Article 的字段?

您可以将逻辑放在 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 指南