如何解决在Rails中,如何在View中构建哈希数组以传递给控制器?
我正在构建一个平台,让用户创建项目。每个项目可能具有不同的角色,并且每个角色可能具有不同的要求,应用到该项目的用户必须满足这些要求(要求是一对Technology和Level对象)。
截至目前,我有这样的事情:
<%= 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,prompt: "Nivel" %>
<% end %>
<%= f.input :name,placeholder: "Nombre del rol" %>
<%= f.input :description,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,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=
设置器,为您解决所有这些问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。