Solution for nested form

前端 未结 2 1195
清歌不尽
清歌不尽 2021-01-28 09:02

I have been stuck on this problem for a while.

Need to make a form for competitions category with custom inputs. It should take all values fro

相关标签:
2条回答
  • 2021-01-28 09:31

    Sounds to me like you're looking for accepts_nested_attributes_for

    See: https://apidock.com/rails/v3.2.3/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for

    https://rubyplus.com/articles/3681-Complex-Forms-in-Rails-5

    Also, check out the cocoon gem.

    0 讨论(0)
  • 2021-01-28 09:37

    Take a look at this gem: https://github.com/plataformatec/simple_form

    Simple Form aims to be as flexible as possible while helping you with powerful components to create your forms.

    Let's take a simple example:

    class Machine < ActiveRecord::Base
    has_many :parts , inverse_of: :machine
    accepts_nested_attributes_for :parts
    end
    
    class Part < ActiveRecord::Base
    # name:string
    belongs_to :machine
    end
    

    With these models, we can use simple_form to update the machine and its associated parts in a single form:

    <%= simple_form_for @machine do |m| %>
      <%= m.simple_fields_for :parts do |p| %>
      <%= p.input :name %>
      <% end %>
    <% end %>
    

    For 'new' action, build the nested model from the controller:

    class MachinesController < ApplicationController
      def new
      @machine = Machine.new
      @machine.parts.build
     end
    end
    

    Source: https://github.com/plataformatec/simple_form/wiki/Nested-Models

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