0

我不知道模板是否是正确的词。我希望具有模板布尔值 true 的模型可以在相同的模型表单视图中进行选择。并且在选择时,它将使用所选模型值填充表格。

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

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

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

编辑。:

对不起,如果它不能理解。

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

_form.html.haml:

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

在选择时,模板模型用旧模板模型的属性填充新模型的属性。

我想为此找到 Rails 方式。

4

2 回答 2

2

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

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

在您的控制器中,加载模板记录并克隆它。不要使用dup,因为那会复制id.

def new
  @model = Model.find_template_record.clone
end
于 2013-06-02T18:56:44.550 回答
0

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

@model = @template_model.dup        # create the base
@model.attributes = params[:model]  # override particular attributes
于 2013-06-02T18:54:25.527 回答