简体   繁体   English

如何将Rails对象作为参数发送到POST请求

[英]how to send Rails object to POST request as a param

I have an rails object named app, when i send it to controller by following method then i get params[:app] as array in the controller. 我有一个名为app的rails对象,当我通过以下方法将其发送到控制器时,我会在控制器中将params [:app]作为数组获取。 I have already tried a lot on stack overflow but did not found what i was looking for 我已经在堆栈溢出上做了很多尝试,但是没有找到我想要的东西

assert_difference("Tagging.count", 3) do
      put "/candidates/#{app.id}", {id: app.id, assigned_tags: " #{tag_one.name} #{tag_two.name} #{tag_three.name} " ,  app: app.to_json }
    end

how can i get the app as hash in controller through params[:app] ?? 我如何通过params [:app]将应用程序作为哈希值添加到控制器中?

There are two data structures you can build with the name attribute of a form field. 您可以使用表单字段的name属性构建两个数据结构。

foo[] will put the value into an array called foo foo[]会将值放入名为foo的数组中

foo[bar] will put the value into a hash called foo , using the key bar . foo[bar]将使用键bar将值放入名为foo的哈希中。

eg 例如

  <input type="text" name="foo[]" value="bacon">
  <input type="text" name="foo[]" value="chicken">
  => params = {:foo => ["bacon", "chicken"]}

  <input type="text" name="foo[bar]" value="bacon">
  <input type="text" name="foo[baz]" value="chicken">
  => params = {:foo => {:bar => "bacon", :baz => "chicken"}}

These can be combined: 这些可以组合:

  <input type="text" name="foo[bar][]" value="bacon">
  <input type="text" name="foo[baz][]" value="chicken">
  => params = {:foo => {:bar => ["bacon"], :baz => ["chicken"]}}

  <input type="text" name="foo[][bar]" value="bacon">
  <input type="text" name="foo[][baz]" value="chicken">
  => params = {:foo => [{:bar => "bacon", :baz => "chicken"}]}

You can't send an object through params. 您无法通过参数发送对象。 Normally you should send the ID of that object in params and in receiving end you should lookup in the controller. 通常,您应该以参数形式发送该对象的ID,在接收端,应该在控制器中进行查找。

user = User.find(params[:user_id])

If you send an object as params, it'll be converted to array automatically. 如果将对象作为参数发送,则它将自动转换为数组。

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

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