通过隐藏字段将数组传递到 Rails
我的表单中有一个像这样的hidden_tag,
<%= f.hidden_field :loc , {:multiple => true} %>
它呈现为
<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="">
当前正在将business_loc值设置为逗号分隔的字符串,希望rails在提交表单时能够识别。但这是我在服务器端获得的值,
"loc"=>["80.22167450000006,13.0454044"]
而不是
"loc"=>[80.22167450000006,13.0454044]
我如何在隐藏字段中设置正确的值,以便rails可以正确理解它。
i have a hidden_tag like this in my form
<%= f.hidden_field :loc , {:multiple => true} %>
which renders to
<input id="business_loc" multiple="multiple" name="business[loc][]" type="hidden" style="color: rgb(175, 175, 175); " value="">
currently am setting the business_loc value as a comma seperated string hoping rails would recognize when submit the form. But this is the value i got on the server side
"loc"=>["80.22167450000006,13.0454044"]
instead
"loc"=>[80.22167450000006,13.0454044]
how do i set the correct value in hidden field, so rails can understand it correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用多个隐藏字段,每个隐藏字段对应值数组的每个元素。
例如:
...如果您需要代码来使用 JS 动态添加这些内容,这里有一个 jQuery 示例:
You need to use multiple hidden fields, one for each element of the array of values.
For example:
...if you need code to dynamically add these with JS, here's a jQuery example:
我发现 text_area 可以使事情正常工作,而无需添加一堆隐藏表单。只需将文本区域的值设置为类似于
[1,31,51,61]
的值,它就应该可以工作,假设您的模型中有serialize :var
I've found text_area's to make things work without having to add a bunch of hidden forms. Just set the value of the text area to something that looks like
[1,31,51,61]
and it should work, assuming in your model you haveserialize :var
我最近也遇到了同样的问题。我的解决方案是通过简单地在逗号处分割数组来在服务器端处理它。就我而言,它看起来像这样:
I had this same problem recently. My solution was to handle it on the server side by simply splitting the array at the comma. In my case it looks like this: