rails 4 article data template

91 views Asked by At

e.g. i have two models generated with scaffold, Template and Article

Template has_many :articles and Article belong_to :template

Template have title:string body:text as fields. Article have title:string body:text template_id:integer as fields.

The question is: how i can use the Template model to prefill the Article's fields when one new is created?

1

There are 1 answers

2
RustComet On BEST ANSWER

You could put the logic in an before_create callback

class Article < ActiveRecord::Base
  belongs_to :template

  before_create :assign_attributes_from_template


  def assign_attributes_from_template
    title = template.title
    # etc
  end
end

This will however run after validation, so if you need to validate these fields you should probably put this in a before_validation, on: :create callback instead.

Hope this helps!

EDIT: Link to callbacks guide