0

我正在构建一个让用户创建项目的平台。每个项目可能有不同的角色需要覆盖,每个角色可能有不同的需求,用户应用到它必须满足(需求是一对技术和级别对象)。

截至目前,我有这样的事情:

<%= simple_form_for([ @project, @role ], remote: true) do |f| %>
   <%= simple_fields_for :requirement do |ff| %>
      <%= ff.input :technology_id, collection: Technology.all, label:false, prompt: "Tecnología" %>
      <%= ff.input :level_id, collection: Level.all, label:false, prompt: "Nivel" %>
   <% end %>

   <%= f.input :name, label:false, placeholder: "Nombre del rol" %>
   <%= f.input :description, label:false, placeholder: "Descripción" %>
   <%= f.submit "Add role", class: "btn btn-primary" %>
<% end %>

但是,这种方法并不方便,因为它只会让我为该角色创建 1 个需求(技术和级别对)。

我怎样才能让用户一次为该角色创建许多不同的需求?我正在考虑构建一个哈希数组并将其传递给控制器​​,这样我就可以对其进行迭代。就像是:

requirements = [{technology: "Ruby", level: "Junior"}, {technology: "Rails", level: "Junior"}..]

但是,我不知道这是否是这样做的方法,如果是这样,是否可以使用 simple_form 来完成。任何见解将不胜感激。

4

1 回答 1

1

你不需要在这里做任何愚蠢的恶作剧。只需要将关联更改为一对多:

class Role < ApplicationRecord
  has_many :requirements
  accepts_nested_attributes_for :requirements
end

class Requirement < ApplicationRecord
  belongs_to :role
  belongs_to :level
  belongs_to :technology
end
<%= simple_form_for([ @project, @role ], remote: true) do |f| %>
   <%= simple_fields_for :requirements do |ff| %>
      <%= ff.input :technology_id, collection: Technology.all, label:false, prompt: "Tecnología" %>
      <%= ff.input :level_id, collection: Level.all, label:false, prompt: "Nivel" %>
   <% end %>
   ...
<% end %>

然后,您需要在控制器中播种关联以显示输入:

def new
  @role = Role.new do |r|
    5.times { r.requirements.new }
  end
end

您可以通过传递与您要允许的属性相对应的符号数组来将嵌套属性数组列入白名单:

def role_params
  params.require(:role)
        .permit(
           :name, :description,
           requirements_attributes: [
             :id, :_destroy, :technology_id, :level_id
           ]
         )
end

你不需要遍历任何东西。accepts_nested_attributes_for :requirements创建一个requirements_attributes=为您处理一切的二传手。

于 2020-08-25T13:39:20.197 回答