1

这是我想用来验证 csv 文件中的列的 RoR 代码。但是“rowdata”数组中的值不会传递给验证方法。任何帮助是极大的赞赏。

#Ruby on Rails code
def validate_rows
    count_row=0
    #@passed_file is a csv file which is read from a submitted html form.
    @parsed_file=CSV::Reader.parse(params[:dump][:csvfile])
    @parsed_file.each  do |row|
        # Array of columns to be validated
        validate_cols = [:admission_no, :class_roll_no]
        rowdata={'admission_no'=>row[0],'class_roll_no'=>row[1]}


        #validate colums by sending value from the array (rowdata)  to a method injected
        #by the following code. However value from rowdata array is not passed
        #to the method.
        if count_row >=1
            valid = validate_cols.inject(true){|valid_sum, col|
                valid_sum && send("validate_#{col}", rowdata[col])
            }
            #if validation fails return row number.
            if not (valid)
                return count_row
            end
        end
        count_row=count_row+1
    end 
    #if validation suceeds return 0
    return 0
end

#The following methods are called by the inject funnction (valid)
def validate_admission_no(passed_value)
    if(passed_value)
        return true
        else
        return false
    end
end

def validate_class_roll_no(passed_value)
    if(passed_value)
        return true
        else
        return false
    end
end
4

1 回答 1

1

我的建议是使用字符串而不是符号

 def validate_rows
count_row=0
#@passed_file is a csv file which is read from a submitted html form.
@parsed_file=CSV::Reader.parse(params[:dump][:csvfile])
@parsed_file.each  do |row|
    # Array of columns to be validated
    validate_cols = ["admission_no", "class_roll_no"]
    rowdata={'admission_no'=>row[0],'class_roll_no'=>row[1]}


    #validate colums by sending value from the array (rowdata)  to a method injected
    #by the following code. However value from rowdata array is not passed
    #to the method.
    if count_row >=1
        valid = validate_cols.inject(true){|valid_sum, col|
            valid_sum && send("validate_#{col}", rowdata["#{col}"])
        }
        #if validation fails return row number.
        if not (valid)
            return count_row
        end
    end
    count_row=count_row+1
end 
#if validation suceeds return 0
return 0

结尾

于 2012-10-31T06:26:46.780 回答