rails 4篇文章数据模板
rails 4 article data template
例如我有两个用脚手架生成的模型,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
的字段?
您可以将逻辑放在 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 指南
例如我有两个用脚手架生成的模型,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
的字段?
您可以将逻辑放在 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 指南