保存模型以便以后用作“模板”的最佳方法

时间:2013-06-02 09:10:49

标签: ruby-on-rails ruby

我不知道模板是否适合这个词。 我想要模板布尔为true的模型,可以在相同的模型窗体视图中选择。在选择时,它将使用所选模型值填充表单。

我正在考虑这个解决方案:

  • 列出模板属性设置为true的表单旁边的模型。
  • 点击加载它通过AJAX,并通过javascript填充带有加载属性的表单。

我想知道是否有更好的方法呢?

编辑:

很抱歉,如果这是不可理解的。

Model.rb具有布尔属性:template。 如果template设置为true。它显示在模型的表单视图中。

_form.html.haml:

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

并在select上,模板模型在新模型的属性中填充旧模板Model的属性。

我想找到Rails的方法。

2 个答案:

答案 0 :(得分:2)

在模型中添加一个类方法以查找模板记录。

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

在您的控制器中,加载模板记录并clone。请勿使用dup,因为这会复制id

def new
  @model = Model.find_template_record.clone
end

答案 1 :(得分:0)

要复制ActiveRecord模型,请使用其dup方法:

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