Ruby on Rails - add fields from a Model on another

2019-02-19 07:09发布

I have two models Contract and Addendum. Contract has_many :addendums and Addendum belongs_to :contract

When a new Contract is created, automatically will create a new Addendum but some aditional elements are needed to create the new Addendum. How can I add a field value, which is an attribute from Addendum but not from Contract, on the Contract's form?

1条回答
小情绪 Triste *
2楼-- · 2019-02-19 07:34

What you're looking for is a nested form, which is pretty common in RoR. For more information on nested and complex forms, there's a section of a Rails Guide for that. I'd recommend checking out all of the Rails Guides, which are incredibly helpful when learning the framework.

For your specific question, first tell your Contract model to accept_nested_attributes_for your Addendum model.

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

Next, open up your contract controller, and do two things. One, build an addendum when making a new contract. Two, allow the nested attributes of addendums (assuming you're using rails 4) in your contract_params method.

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

Last, add the forms_for helper in your contracts form.

<%= 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 %>

With that, you should be all set! Happy coding!

查看更多
登录 后发表回答