Question

I have BaseProject, ProjectTemplate and Project

class ProjectTemplate << BaseProject; end
class Project << BaseProject; end

I would like to copy project_template attributes to a new project instance as defaults.

The problem is if i use dup project will have type set to ProjectTemplate

project_template = ProjectTemplate.first
project = project_template.dup

i can set the type by hand

project.type = "Project"

but i don't like it that way, or i can do this

project_template = ProjectTemplate.first
project = Project.new( project_template.attributes.except("id", "type") )

but i read this question which recommends against the second solution.

What whould be the recommended way to solve this issue?

Was it helpful?

Solution

I don't think there's going to be a "better" way that the dup, type= approach. You could create a class method on Project that you can then use whenever you need to create a project:

class Project < BaseProject
  def new_from_template(template)
    project = template.dup
    project.type = 'Project'
    project
  end
end

Then you would just need to use this:

project = Project.new_from_template(ProjectTemplate.first)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top