Barna Kovacs
Barna Kovacs

Reputation: 1276

Best way to save the model to use later as "template"

I don't know if template is the right word for this. I want models which has template boolean true, to be choose-able at the same models form view. And on choose it would fill the form with the chosen models values.

I'm thinking about this solution:

I'm wondering if there is a better way for this?

Edit.:

Sorry if it wasn't understandable.

Model.rb has boolean attribute :template. If template is set to true. It is displayed on the form view of the Model.

_form.html.haml:

:collection_select Model.where(:template => true)

and on select, the template model fills, in the new Model's attributes, with the old template Model's attributes.

I would like to find the Rails way for this.

Upvotes: 0

Views: 121

Answers (2)

Jared Beck
Jared Beck

Reputation: 17528

Add a class method in your model to find the template record.

def self.find_template_record
  template = where(template: true).first
  raise "no template found" if template.nil?
  return template
end

In your controller, load the template record and clone it. Don't use dup because that will copy the id.

def new
  @model = Model.find_template_record.clone
end

Upvotes: 2

Matchu
Matchu

Reputation: 85812

To duplicate an ActiveRecord model, use its dup method:

@model = @template_model.dup        # create the base
@model.attributes = params[:model]  # override particular attributes

Upvotes: 0

Related Questions