Ruby on Rails - add fields from a Model on another Model's form

后端 未结 1 510
耶瑟儿~
耶瑟儿~ 2021-01-14 23:56

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

When a ne

相关标签:
1条回答
  • 2021-01-15 00:48

    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!

    0 讨论(0)
提交回复
热议问题