[英]In Rails, how would you build an array of hashes in the View to pass to the controller?
我正在構建一個讓用戶創建項目的平台。 每個項目可能有不同的角色需要覆蓋,每個角色可能有不同的需求,用戶申請它必須滿足(需求是一對技術和級別對象)。
截至目前,我有這樣的事情:
<%= 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 來完成。 任何見解將不勝感激。
你不需要在這里做任何愚蠢的惡作劇。 只需要將關聯改為一對多:
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=
setter 來為你處理這一切。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.