简体   繁体   English

使用参数值作为轨道上的循环范围红宝石

[英]Use param value as loop range ruby on rails

Controller return error "bad value for range" when passing param as loop range limit, following is my code 传递参数作为循环范围限制时,控制器返回错误“范围的错误值”,以下是我的代码

def creategroups
  require 'fileutils'
  @gcount = params[:group_count]
  for i in (1..@gcount) do
    Fileutils::mkdir_p "/groups/group_#{i}"
  end
  render json: params
end

here group_count is the number of groups to be created. 这里group_count是要创建的组数。

When you fetch a parameter from the request, the value is generally a String. 从请求中获取参数时,该值通常为字符串。 Therefore, in the following line @gcount is a String, not an integer. 因此,在下面的行中, @gcount是字符串,而不是整数。

@gcount = params[:group_count]

You need to cast it. 您需要投射它。 Moreover, in Ruby you never use the for loop, rather you use blocks. 此外,在Ruby中,您永远不要使用for循环,而要使用块。

require 'fileutils'

def creategroups
  gcount = params[:group_count].to_i
  gcount.times do |index|
    Fileutils::mkdir_p "/groups/group_#{index}"
  end
  render json: params
end

or to keep it shorter 或保持较短

require 'fileutils'

def creategroups
  params[:group_count].to_i.times do |index|
    Fileutils::mkdir_p "/groups/group_#{index}"
  end
  render json: params
end

Of course, you may want to validate :group_count to avoid someone passes a gigantic number that will kill your system. 当然,您可能需要验证:group_count以避免有人通过一个巨大的数字来杀死您的系统。

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

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