我试图解析句子并将每个单词保存在数据库中,并计算每个单词出现的次数。为此,我有一个QTreeWidgetItem
模型,其中包含Info
和word
属性。如果count
存在,请增加word
;如果没有,请创建count
并将word
设置为count
。简单,对吧?
好。这是相关代码:
1
这会返回以下错误:
def parse entry
word = entry[:base]
if Info.exists?(word: word)
old_word = Info.where(word: word)
new_count = old_word.count + 1
old_word.count = new_count
old_word.save
else
new_word = Info.new(word: word, count: 1)
new_word.save
end
end
我很确定我之前已经使用过这种语法,根据correct BUILD file,它应该有用:
NoMethodError (undefined method `count=' for #<Info::ActiveRecord_Relation:0xb7c83e8>
Did you mean? count):
但同一操作的语法不同,所以让我们试一试:
user = User.find_by(name: 'David')
user.name = 'Dave'
user.save
现在它起作用了,Rails并没有抱怨并创建了记录。但是,它仅更新def parse entry
word = entry[:base]
if Info.exists?(word: word)
old_word = Info.where(word: word)
new_count = old_word.count + 1
old_word.update(count: new_count)
else
new_word = Info.new(word: word, count: 1)
new_word.save
end
end
最多count
个实例。除此之外,根本没有任何反应。这是一个例子:
使用新单词2
插入第一个句子:
new
您可以看到它检查单词是否存在,然后创建新记录。
使用现有的单词Info Exists (0.0ms) SELECT 1 AS one FROM "infos" WHERE "infos"."word" = ? LIMIT ? [["word", "new"], ["LIMIT", 1]]
(0.0ms) begin transaction
SQL (2.0ms) INSERT INTO "infos" ("word", "count", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["word", "new"], ["count", 1], ["created_at", "2018-01-16 20:20:38.078146"], ["updated_at", "2018-01-16 20:20:38.078146"]]
(130.1ms) commit transaction
插入第二句:
new
您可以看到它检查单词是否存在,看到它已经存在,因此开始使用新计数更新记录的交易。
现在,当您插入单词Info Exists (1.0ms) SELECT 1 AS one FROM "infos" WHERE "infos"."word" = ? LIMIT ? [["word", "new"], ["LIMIT", 1]]
(1.0ms) SELECT COUNT(*) FROM "infos" WHERE "infos"."word" = ? [["word", "new"]]
Info Load (0.0ms) SELECT "infos".* FROM "infos" WHERE "infos"."word" = ? [["word", "new"]]
(0.0ms) begin transaction
SQL (4.0ms) UPDATE "infos" SET "count" = ?, "updated_at" = ? WHERE "infos"."id" = ? [["count", 2], ["updated_at", "2018-01-16 20:21:28.310815"], ["id", 5]]
(14.0ms) commit transaction
第三时,会发生这种情况:
new
你可以看到它检查单词的存在,看它已经存在,只是看似忽略了Info Exists (1.0ms) SELECT 1 AS one FROM "infos" WHERE "infos"."word" = ? LIMIT ? [["word", "new"], ["LIMIT", 1]]
(0.0ms) SELECT COUNT(*) FROM "infos" WHERE "infos"."word" = ? [["word", "new"]]
Info Load (0.0ms) SELECT "infos".* FROM "infos" WHERE "infos"."word" = ? [["word", "new"]]
(0.0ms) begin transaction
(0.0ms) commit transaction
命令。 update
属性从现在开始就停止更新。
发生了什么事?我错过了什么或者这是一个错误吗?