我正在创建一个接受用户文件并逐行读取文件的操作。每行包含几个单词,用逗号分隔。 想法是读取每一行,将行转换为字符串数组,然后单独处理每个单词。
我创建了一个名为Word的基本类,它只有一个ID和值。 我还有一个名为Synonym的基本类,它有一个ID,值和word_id来链接到一个单词。
解析单词时收到异常:
undefined method `to_f' for
#<Array:0x7ff6627074d8>
这是导致我这个问题的代码:
# Processes the uploaded file from the upload form and extracts
# all relevant information from the file to store it in the database
def process_upload
path = params[:file].tempfile.path
open(path).each do |line|
words = line.trim.split(',')
first_word = words.first
# Check if the word already exists as a synonym. If the word is a known synonym, save the
# remaining words as synonyms for the parent word. But only save these words if they don't
# exist yet
if !Synonym.find_by_value(first_word).blank?
parent_id = Synonym.find_by_value(first_word).word_id
words.each do |word|
Synonym.create(:value => word, :parent_id => parent_id) if Synonym.find_by_value(word).blank?
end
end
# Check if the first word is already known as a word inside the application. If the first word is already
# a known word, append all remaining words to the word as a synonym, but only if they don't exist yet.
if !Word.find_by_value(first_word).blank?
words.each do |word|
parent_id = Word.find_by_value(first_word).id
if (word != first_word) and Synonym.find_by_value(word).blank?
Synonym.create(:value => word, :parent_id => parent_id)
end
end
end
# The word is not a known synonym, and not a known word. Create the word in the database and
# append all remaining words to the database as synonyms.
word = Word.create(:value => first_word)
words.each do |w|
if w.eql? word.value
Synonym.create :value => w, :parent_id => word.id
end
end
end
end
问题发生在最后一部分,Word.create(:value =&gt; first_word) 我在这里收到一个异常,试图将它转换为浮动因为某些原因,但我不知道为什么。
两种模型的迁移模式:
class CreateWords < ActiveRecord::Migration
def self.up
create_table :words do |t|
t.string :value, :null => false
t.timestamps
end
end
def self.down
drop_table :words
end
end
class CreateSynonyms < ActiveRecord::Migration
def self.up
create_table :synonyms do |t|
t.integer :word_id, :null => false
t.string :value, :null => false
t.timestamps
end
end
def self.down
drop_table :synonyms
end
end
我错过了什么?
答案 0 :(得分:2)
关于上述评论,我发现了导致这种情况的原因:
如果您依赖rubyforge或rubygems中的Classifier gem,它将覆盖Array#sum方法。由于这些gems是在加载AFTER后加载的,因此它们也会覆盖ActiveRecord的这种方法,这会导致错误。
有这个宝石的分支跟踪所有这些,但最后,我决定使用'Ankusa'宝石,因为它更适合处理大批量的文本数据并具有更好的集成支持为了拯救国家。