【问题标题】:How to have multiple forms for one model in one view如何在一个视图中为一个模型创建多个表单
【发布时间】:2021-10-11 15:00:51
【问题描述】:

我需要通过以一种形式将所有与游戏相关联的作业设置为游戏的作业。当我进入 edit_assignment 页面时,虽然只有 1 个输入。例如,如果我有 3 个作业,在一场比赛中。如何构建表单以显示 3 个输入 AKA 3 个作业?可能还值得注意的是,我希望渲染与为每个游戏创建的分配一样多的输入。

我尝试了一些类似的方法无济于事:

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

型号:

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

【问题讨论】:

标签: ruby-on-rails forms model simple-form


【解决方案1】:

如果游戏有 x 个任务,您正在做的是为每个任务渲染 x 次表单。您需要 x 个输入字段,而不是呈现表单,因此不要循环表单,而是为每个具有不同分配 id 的分配循环输入字段,如下所示:

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

【讨论】:

  • 当我将它嵌套在游戏表单中时,它起作用了。将弄清楚如何让它自己显示。谢谢
猜你喜欢
  • 2021-12-19
  • 2022-08-13
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多