我在控制器中有这个:
Offer
我希望能够显示一条通知,说明进口了4件事。"例如。但我不知道如何从操作中提取插入的记录数。
是否有内置方法可以找到与数据库无关的内容?
答案 0 :(得分:0)
答案 1 :(得分:0)
实际上有3种获取此信息的方法:length
,count
和size
<强> collection.count 强>
count
结果未存储在内存中。这意味着,每次调用此methis时,它都会提交一个新查询!
collection = Record.all.count #> SELECT COUNT(*) FROM `records`
<强> collection.length 强>
该集合必须在内存中才能使其正常工作
collection = Record.all.length #> Record Load (122.9ms) SELECT `records`.* FROM `records`
<强> collection.size 强>
count
和length
)如果集合不在内存中,它将运行SQL查询并count
collection = Record.all
collection.count # > SELECT COUNT(*) FROM `records`
collection.count # > SELECT COUNT(*) FROM `records`
collection.size # > SELECT COUNT(*) FROM `records`
collection.to_a.size # > Record Load SELECT `records`.* FROM `records`
答案 2 :(得分:0)
这就是我最终做的事情:
# app/models/mymodel.rb
class MyModel < ActiveRecord::Base
def self.import(csv_file)
create_count = 0
CSV.foreach(csv_file.path, headers: true) do |row|
Model.create! row.to_hash
create_count += 1
end
return create_count
end
end
# app/controllers/mycontroller.rb
class MyController < ApplicationController
def import
begin
created_count = MyModel.import(params[:file])
redirect_to root_url, notice: "#{created_count} things imported."
rescue
redirect_to root_url, error: "Couldn't import CSV file, nothing imported."
end
end
end
另一种可能也有效的实现:
# app/controllers/mycontroller.rb
class MyController < ApplicationController
def import
begin
before_count = MyModel.count
MyModel.import(params[:file])
after_count = MyModel.count
added_count = before_count - after_count
redirect_to root_url, notice: "#{added_count} things imported."
rescue
redirect_to root_url, error: "Couldn't import CSV file, nothing imported."
end
end
end