Search code examples
ruby-on-railsformsmodelsimple-form

How to have multiple forms for one model in one view


I need to set the Assignments on a Game by having all assignments associated to a game in one form. When I go to the edit_assignment page though there's only 1 input. If I have 3 assignments, for example, on one game. How do I structure the form to display the 3 inputs AKA the 3 assignments? It's probably also worth noting that I'd want to render as many inputs as there are assignments created for each game.

I tried something along the lines of this to no avail:

<%= @game.assignment do |a| %>
  <div>
    <%= simple_form_for(a) do |f| %>
      <%= f.error_notification %>
      <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

    <div class="form-inputs">
      <%= f.input :user_id, label: "C: " do %>
        <%= f.select :user_id, User.all.map { |r| [r.first_name, r.id] }, {include_blank: "Select Referee" } %>
      <% end %>
    </div>
    <% end %>
  </div>
<% end %>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

Models:

class Game < ApplicationRecord
    has_many :assignments
    has_many :users, through: :assignments
end
class Assignment < ApplicationRecord
    belongs_to :game
    belongs_to :user
end

Solution

  • What you are doing is rendering the form x times for each assignment if a game has x assignments. Instead of rendering form you need x input fields, so instead of looping form, loop the input fields for each assignment with different assignment id, something like this:

    <div>
        <%= form_with @game do |f| %>
            <%= form.fields_for :assignments do |assignment| %>
                <%= assignment.input :user_id, label: "C: " do %>
                <%= assignment.select :user_id, User.all.map { |r| [r.first_name, r.id] }, {include_blank: "Select Referee" } %>
            <% end %>
        <% end %>
    </div>