简体   繁体   English

Rails 5:如何发送多个记录的发布请求

[英]Rails 5: How to send a post request for multiple records

This is what I am trying to do: 这就是我想要做的:

= form_tag(path) do
    - @items.each do |i|
        = fields_for "i[]", i do
            %input.content{:name => "content", :type => "hidden"}
    = submit_tag "Submit"

As you can see, I try to pass the value of all .content inputs from items to a path. 如您所见,我尝试将所有.content输入的值从items传递到路径。

These are the parameters I get: 这些是我得到的参数:

{"utf8"=>"✓", "content"=>"", "commit"=>"Submit"}

I'd expect something like this: 我希望这样的事情:

{"items": [
    {
        "id":1,
        "content":""
    },
    {
        "id":2,
        "content":""
    },
    {
        "id":3,
        "content":""
    },
] }

How do you create those POST requests in rails? 如何在Rails中创建那些POST请求?

This is simpler than you've been trying to make it. 这比您尝试做的要简单。 You tend to only need fields_for if you have a set of fields for each of the nested models. 如果每个嵌套模型都有一组字段,则倾向于只需要fields_for here you just have a single hidden column, so I'd choose to just use a single hidden field eg: 在这里,您只有一个隐藏的列,所以我选择仅使用一个隐藏的字段,例如:

= form_tag(path) do |f|
    - @items.each do |i|
      = f.hidden_field "items[#{i.id}]", value: i.content
    = submit_tag "Submit"

Note: not bug-testing left as an exercise to the reader. 注意:不进行错误测试是读者的练习。

This will generate a set of parameters that map the id of the item vs the content eg: "items"=>{"38383285"=>"", "304713261"=>"Some content here", "547539357"=>"Some other content here"} 这将生成一组参数,这些参数将项目的ID与内容相对应,例如: "items"=>{"38383285"=>"", "304713261"=>"Some content here", "547539357"=>"Some other content here"}

Which you can just iterate through to change the actual values however you like. 您可以随意迭代以更改实际值。

You have not provided any example of the actual structure of your models - so I am guessing how you would use that... you will need to (possibly heavily) modify the example below to meet your actual needs. 您尚未提供模型实际结构的任何示例-因此我猜测您将如何使用它...您将(可能需要大量修改)下面的示例以满足您的实际需求。 For one thing - given it's a hidden field - I have no idea what other model (and column) it is that you are trying to update. 一方面-考虑到它是一个隐藏字段-我不知道您要更新的其他模型(和列)。 So lets pretend you have a second model called OtherItem that also has a content-field and maps to an Item via an item_id column. 因此,假设您有另一个名为OtherItem模型,该模型还具有一个内容字段,并通过item_id列映射到Item In that case, you'd do something like this: 在这种情况下,您将执行以下操作:

def my_action
  item_ids = params[:items].keys
  items = OtherItem.where(:item_id => item_ids)
  items.each do |item|
    item.update(content: params[:items][item.item_id])
  end
  # other stuff here

end 结束

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM