Ruby on Rails 在变量名中使用计数器,即“i" [英] Ruby on Rails using counter, i.e. "i", in a variable name

查看:35
本文介绍了Ruby on Rails 在变量名中使用计数器,即“i"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 中有一个表单,用户可以在其中输入多条记录.我将编写一些 JavaScript,用户可以在其中拥有几乎无限数量的记录.我的哈希看起来像这样:

I have a form in Rails where users can enter multiple records. I am going to write some JavaScript where users can have a virtually unlimited number of records. My hash is going to look like this:

inputA_1, inputB_1, inputC_1
inputA_2, inputB_2, inpuctC_2

在我的控制器中,我想做一个 while 循环来遍历行并将它们保存到数据库中,例如:

In my controller I want to do a while loop to iterate through the rows and save them to the database, for example:

z = 0
i = 1
while z = 0
  @inputA = [:params][:inputA_i]
  @inputB = [:params][:inputB_i]
  @inputC = [:params][:inputC_i]
  if @inputA.nil?
     z=1
  else
  @record = [inputA: @inputA, inputB: @inputB, inputC: @inputC]
  @record.save
  i = i + 1
  end
end

问题是我不知道如何让:inputA_ii"成为i的值.

The problem is that I don't know how to make the "i" of :inputA_i be the value of i.

对此的任何帮助将不胜感激.

Any help in that would be appreciated.

推荐答案

i 内插为字符串并将字符串转换为 symbol :

Interpolate i into a string and convert string to symbol:

@inputA = [:params]["inputA_#{i}".to_sym]
@inputB = [:params]["inputB_#{i}".to_sym]
@inputC = [:params]["inputC_#{i}".to_sym]

这篇关于Ruby on Rails 在变量名中使用计数器,即“i"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆