Solution for nested form

前端 未结 2 1224
清歌不尽
清歌不尽 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: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

提交回复
热议问题