rails 包含多个字段的数组

rails array with multiple fields

我正在尝试创建一个具有多个内部字段的数组,以便在渲染时我可以保存每个字段,如下所示:

@profile = [{module:"user", Description:"module of users"},{module:"products", Description:"module of products"}]

以这种方式呈现和创建记录:

@profile.each do |prof|
    Record.create(module: prof.module, Description: prof.descripcion)
end

但我收到此错误:

NoMethodError (undefined method `module' for {:module=>"users", :description=>"module of users"}:Hash):
  app/controllers/usuarios_controller.rb:31:in `block in busqueda_usuario_perfil'
  app/controllers/usuarios_controller.rb:30:in `each'
  app/controllers/usuarios_controller.rb:30:in `busqueda_usuario_perfil'

要访问哈希,请使用方括号而不是点。

尝试使用这个:

@profile.each do |prof|
  Record.create(module: prof['module'], Description: prof['Description'])
end

它是一个散列,键是符号,所以你需要使用h[:s]:

@profile.each do |prof|
  Record.create(module: prof[:module], description: prof[:descripcion])
end

但由于键值相等,您可以做得更好:

@profile.each do |prof|
  Record.create(prof)
end

我会用小写字母作为键。