现在项目有个批量存储本地图片的需求,查询了 carrierwave 具有存储本地图片的功能,代码实现 v1
@images = Dir.glob("some/local/path/*.jpeg")
@images.each do |file|
image=Image.new
image.file = [Pathname.new(file).open];
image.save
end
虽然功能能实现,但是每次都只能单条插入,很容易想到同时多条插入效率肯定更高点,想到了 buck_insert 这个 gem,然后代码实现 v2
@images = Dir.glob("some/local/path/*.jpeg")
Image.bulk_insert(set_size: 100) do |worker|
@images.each do |file|
worker.add({ file: Pathname.new(file).open })
end
end
然后后台无情的甩出了 TypeError (can't quote File):的错误,具体错误的意思应该是不支持 File 这种类型
/home/ubuntu/.rvm/gems/ruby-2.4.0@rails5/gems/activerecord-5.1.2/lib/active_record/connection_adapters/abstract/quoting.rb
def _quote(value)
case value
when String, ActiveSupport::Multibyte::Chars
"'#{quote_string(value.to_s)}'"
when true then quoted_true
when false then quoted_false
when nil then "NULL"
# BigDecimals need to be put in a non-normalized form and quoted.
when BigDecimal then value.to_s("F")
when Numeric, ActiveSupport::Duration then value.to_s
when Type::Binary::Data then quoted_binary(value)
when Type::Time::Value then "'#{quoted_time(value)}'"
when Date, Time then "'#{quoted_date(value)}'"
when Symbol then "'#{quote_string(value.to_s)}'"
when Class then "'#{value}'"
else raise TypeError, "can't quote #{value.class.name}"
end
end
请教一下各自有什么高效的批量存储本地图片到数据库方法,数据库使用的 pg