Ruby - 数组的错误输出
我有一个包含很多这些文本输入的表单:
<%= text_field_tag 'name[seq]['+dat.id.to_s+']', dat.seq%>
发送此表单后,我想将它们保存到数据库中,我尝试从每个循环中的输入获取值:
unless params[:name].nil?
params[:name][:seq].each_with_index do |sq, i|
puts sq
end
end
但是终端中的输出是错误的,例如,如果我有一个输入值
<%= text_field_tag '名称[seq][25]', 3%>
所以我预计输出是 3,但我会终端这个:
25
3
这里有什么重要的东西,我没有看到吗?
I have a form with a lots of these text inputs:
<%= text_field_tag 'name[seq]['+dat.id.to_s+']', dat.seq%>
After send this form I want to save them to database, I try to get the values from inputs in each loop:
unless params[:name].nil?
params[:name][:seq].each_with_index do |sq, i|
puts sq
end
end
But the output in terminal is wrong, for example if I have an input with the values
<%= text_field_tag 'name[seq][25]', 3%>
So I am going to expect the output is 3, but I will get to terminal this:
25
3
Is here something important, what I don't see?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,你错过了一些东西。在您的
each_with_index
块中,sq
将是一个数组,这就是您获得该输出的原因。那么,这是怎么回事?好吧,您的
params
将包含以下内容:这意味着
params[:name][:seq]
是这样的:然后您将
each_with_index
应用于迭代哈希。如果你这样做:你就会看到发生了什么。
如果您只想要
3
那么您可以像上面一样迭代params[:name][:seq]
并只查看v
内的阻止,或者,如果您知道'25'
是什么其他方式,您可以直接转到那里:Yes, you are missing something. Within your
each_with_index
block,sq
will be an array and that's why you get that output.So, what's going on here? Well, your
params
will contain this:And that means that
params[:name][:seq]
is this:Then you apply
each_with_index
to that to iterate through the Hash. If you do it like this:you'll see what's going on.
If you just want the
3
then you can iterate overparams[:name][:seq]
as above and just look atv
inside the block or, if you know what the'25'
is some other way, you could just go straight there: