Rails - 简单循环不工作

时间:2013-08-06 21:19:58

标签: ruby-on-rails ruby

在我的控制器中,我试图在表格中进行批量插入,在我的第一次尝试中它可以工作,但名称会以某种方式被破坏,如下所示:(循环运行24次,这就是我想要的)

test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11
test-port-name-0-1-2-3-4-5-6-7-8-9-10
test-port-name-0-1-2-3-4-5-6-7-8-9
test-port-name-0-1-2-3-4-5-6-7-8
test-port-name-0-1-2-3-4-5-6
test-port-name-0-1-2-3-4-5-6-7
test-port-name-0-1-2-3-4-5
test-port-name-0-1-2-3-4
test-port-name-0-1-2
test-port-name-0-1-2-3
test-port-name-0
test-port-name-0-1
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22
test-port-name-0-1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23

而不是test-port-name-0 .... test-port-name-23

def bulk_port_import
  if request.post?
    #attempt create
    count = 0
    for i in 1..session[:no_ports]
      params[:dp][:name] = params[:dp][:name] + '-' + count.to_s
      @dp = DevicePort.create params[:dp]
      count = count + 1
    end
  end
 @success = "Saved." if @dp.valid?
  @error = ""
  @dp.errors.each_full {|e| @error += e + ", "}
  redirect_to '/device/update/' + params[:dp][:device_id]
end

不同的尝试:

def bulk_port_import
  if request.post?
    #attempt create
    i = 0
    while i < session[:no_ports] do
      params[:dp][:name] = params[:dp][:name] + '-' + i.to_s
      @dp = DevicePort.create params[:dp]
      i++
    end
  end
  session.delete(:no_ports)
  @success = "Saved." if @dp.valid?
  @error = ""
  @dp.errors.each_full {|e| @error += e + ", "}
  redirect_to '/device/update/' + params[:dp][:device_id]
end

但有了这个,我得到了syntax error, unexpected kEND,我无法看到我在哪种情况下做错了,这可能是愚蠢的事情。

1 个答案:

答案 0 :(得分:2)

因为你正在改变循环中的params [:dp] [:name]

def bulk_port_import
  if request.post?
    #attempt create
    count = 0
    for i in 1..session[:no_ports]
      dp_name = params[:dp][:name] + '-' + count.to_s
      @dp = DevicePort.create(params[:dp].merge(:name => dp_name))
      count = count + 1
    end
  end
  @success = "Saved." if @dp.valid?
  @error = ""
  @dp.errors.each_full {|e| @error += e + ", "}
  redirect_to '/device/update/' + params[:dp][:device_id]
end