Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何从窗体中获取对象数组?_Ruby On Rails_Ruby On Rails 4_Form For - Fatal编程技术网

Ruby on rails 如何从窗体中获取对象数组?

Ruby on rails 如何从窗体中获取对象数组?,ruby-on-rails,ruby-on-rails-4,form-for,Ruby On Rails,Ruby On Rails 4,Form For,假设我有一个训练模型,它有许多项目。另外,训练接受项目的嵌套属性。使用form_for我希望以以下方式在数组中发送项的参数: "workout"=>{"workout_title"=>"title", "items"=>{ ["name"=>"first item", "name"=>"second item"] } } 但出于某种原因,我只能这样得到它 "workout"=>{"workout_title"=>"title",

假设我有一个训练模型,它有许多项目。另外,训练接受项目的嵌套属性。使用form_for我希望以以下方式在数组中发送项的参数:

"workout"=>{"workout_title"=>"title",
  "items"=>{
    ["name"=>"first item", "name"=>"second item"]
  }
 }
但出于某种原因,我只能这样得到它

 "workout"=>{"workout_title"=>"title",
   "items"=>{"name"=>"second_item"}
 }
我怎样才能解决这个问题

下面是生成上述参数的表单

= form_for :workout, url: welcome_index_path, method: :post do |f|
  = f.text_field :workout_title
  = f.fields_for :items, child_index: 1 do |builder|
    = builder.text_field :name
  = f.fields_for :items, child_index: 2 do |builder|
    = builder.text_field :name, id: 'workout_items_name_2', name: 'workout[items][name]'
  = f.submit 'Go'

为什么不让的
字段为您生成所有项目

= form_for @workout, url: welcome_index_path, method: :post do |f|
  = f.text_field :title
  = f.fields_for :items do |builder|
    = builder.text_field :name
  = f.submit 'Go'

它将显示
@workout
中所有项目的文本字段。此外,您将在
params[:workout][:item_attributes]
中接收项目。另外,Rails'
@post.save(params[:workout])
也将创建相关项目。

您没有将
名称:'workout[items][name]
放在第一个
生成器中。文本字段
@PetrGazarov在这种情况下,只发送第二个参数。删除
名称:'workout[items][name]“
并在强参数中为其指定
名称[]
.PG::UndefinedTable:错误:关系“项”不存在。当我将:workout更改为@workout时,会发生此错误。错误表示您没有“项目”表。在你的问题中,你提到你有。我猜是运行迁移。在这种情况下,我只有一个输入,它通过“锻炼”=>{“锻炼标题”=>“标题”}发送。您在编辑表单中看到您的项目了吗?在您的控制器中,您是否正在筛选您的
参数
参数要求(:训练)。允许(:名称)
)?嗯。。。真奇怪。你能给我们看看呈现的HTML格式吗?