加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 用于nil的未定义方法`fetch_value’:使用Roo

发布时间:2020-12-17 01:55:08 所属栏目:百科 来源:网络整理
导读:我正在尝试使用Roo将Excel电子表格中的数据导入Rails应用程序中的表(data_points). 我收到错误: undefined method `fetch_value' for nil:NilClass 并且该错误在行引用了我的data_point.rb文件(参见下面的完整代码摘录): data_point.save! “应用程序跟踪
我正在尝试使用Roo将Excel电子表格中的数据导入Rails应用程序中的表(data_points).

我收到错误:

undefined method `fetch_value' for nil:NilClass

并且该错误在行引用了我的data_point.rb文件(参见下面的完整代码摘录):

data_point.save!

“应用程序跟踪”说:

app/models/data_point.rb:29:in `block in import'
app/models/data_point.rb:19:in `import'
app/controllers/data_points_controller.rb:65:in `import'

我很困惑,因为我的整个应用程序中的“查找所有”都没有显示fetch_value的实例

这是我的应用程序中的其他代码:

在我的模型中,data_point.rb:

class DataPoint < ActiveRecord::Base
attr_accessor :annual_income,:income_percentile,:years_education

def initialize(annual_income,income_percentile,years_education)
    @annual_income = annual_income
    @income_percentile = income_percentile
    @years_education = years_education
end

def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..11).each do |i| 
        annual_income = spreadsheet.cell(i,'A')
        income_percentile = spreadsheet.cell(i,'B')
        years_education = spreadsheet.cell(i,'C')
        data_point = DataPoint.new(annual_income,years_education)
        data_point.save!
    end
end 

def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".xlsx" then Roo::Excelx.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
end
end

在我的控制器中,我添加了data_points_controller.rb,除了标准的rails框架:

def import
    DataPoint.import(params[:file])
    redirect_to root_url,notice: "Data points imported."
end

在我正在使用的Excel文件中,标题行的列名与上面提到的DataPoints的3个属性完全相同:annual_income,years_education

附:我已经看过RailsCast 396:导入CSV和Excel,并多次阅读评论.我认为我正在努力将示例代码转换为Rails 4和/或我对各个属性的分配(与RailsCast中使用的方法相比).

在此先感谢您的帮助!

解决方法

正如我们在评论中发现的那样,你的非轨道练习似乎有一些剩余物.值得注意的是,覆盖的initialize方法和每个属性的attr_accessor.只需要删除它们(并将DataPoint.new()修复为正确的格式).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读