2013-08-06 36 views
0

在我的控制器我试图做一个批量插入到一个表中,在我第一次尝试它的作品,但名称以某种方式被弄乱如下:(循环运行24次这是我想要的)Rails - 简单的循环不工作

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,我看不出在这两种情况下我做错了什么,它可能再次是愚蠢的。

回答

2

它,因为你正在改变PARAMS [:DP] [:名字]在循环

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 
+0

谢谢你,该诀窍 – martincarlin87