Ruby on Rails - 在另一个Model的表单中添加Model中的字段

时间:2014-06-19 00:40:49

标签: ruby-on-rails forms custom-fields

我有两个模型ContractAddendum。合同has_many :addendums和附录belongs_to :contract

创建新合同时,将自动创建新的附录,但创建新附录需要一些附加元素。如何在合同表格中添加字段value,这是来自附录的属性,而不是来自合同的属性?

1 个答案:

答案 0 :(得分:7)

您正在寻找的是嵌套表单,这在RoR中非常常见。有关嵌套和复杂表单的更多信息,有一个section of a Rails Guide for that。我建议查看所有Rails Guides,这在学习框架时非常有用。

对于您的具体问题,请先告诉您的Contract模型accept_nested_attributes_for您的Addendum模型。

class Contract < ActiveRecord::Base
  has_many :addendum
  accepts_nested_attributes_for :addendums
end

接下来,打开你的合同控制器,做两件事。一,在制作新addendum时构建contract。第二,在addendums方法中允许contract_params的嵌套属性(假设您使用的是rails 4)。

class ContractController < ApplicationController
  def new
    @contract = Contract.new
    @addendum = @contract.addendums.build
  end

  protected
    def contract_params
      params.require(:contact).permit(:field1, :field2, addendums_attributes: [:id, :value, :other_field])
    end
end

最后,在forms_for表单中添加contract帮助程序。

<%= form_for @contract do |f| %>

  <!-- contract fields -->

  Addendums:
  <ul>
    <%= f.fields_for :addendums do |addendums_form| %>
      <li>
        <%= addendums_form.label :value %>
        <%= addendums_form.text_field :value %>

        <!-- Any other addendum attributes -->

      </li>
    <% end %>
  </ul>
<% end %>

有了这个,你应该全力以赴!快乐的编码!

相关问题