0

In my controller I am trying to do a bulk insert into a table, in my first attempt it works but the names somehow get mangled as the following: (loop runs 24 times which is what I want)

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

instead of 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

Different attempt:

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

but with this I get syntax error, unexpected kEND and I can't see what I'm doing wrong in either case, it's probably something stupid, again.

4

1 回答 1

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
于 2013-08-06T21:26:22.357 回答