相关疑难解决方法(0)

批量插入导轨3

我想从我的Rails应用程序中将几千条记录批量插入数据库(在我的情况下为POSTGRES).

这样做的"Rails方式"是什么?一些快速且正确的方法.

我知道我可以通过字符串连接属性来创建SQL查询,但我想要一个更好的方法.

ruby activerecord ruby-on-rails ruby-on-rails-3 rails-postgresql

38
推荐指数
2
解决办法
3万
查看次数

批量将记录插入Active Record表

我发现Model.create!当我一次添加大量记录时,我的陈述需要很长时间才能运行.看看ActiveRecord-Import但是它没有使用哈希数组(这是我拥有的,我认为这很常见).如何提高性能?

activerecord bulkinsert ruby-on-rails

15
推荐指数
4
解决办法
3万
查看次数

如何在 Active Record 中检索用于批量插入的已创建 ID 列表?

我有三个模型:

class Coupon < ActiveRecord::Base
  belongs_to :event
  has_many :coupon_events, :dependent => :destroy
  has_many :events, :through => :coupon_events
end 

class Event < ActiveRecord::Base
  belongs_to :event
  has_many :coupon_events, :dependent => :destroy
  has_many :coupons, :through => :coupon_events
end

class CouponEvent < ActiveRecord::Base
  belongs_to :coupon
  belongs_to :event
end
Run Code Online (Sandbox Code Playgroud)

我通读了一个 CSV 文件来创建优惠券和coupon_events。这是非常低效的,因为一次创建一个记录并导致多个查询,每个查询包括两个插入语句。

我想使用这样的单个插入查询:

coupon_string = " ('abc','AAA'), ('123','BBB')"
Coupon.connection.insert("INSERT INTO coupons (code, name) VALUES"+coupon_string)
Run Code Online (Sandbox Code Playgroud)

然后我需要为 CouponEvent 模型创建第二个插入查询,但我需要一个返回的coupon_ids 的列表。是否有内置方法可以在插入时检索 ID?

mysql activerecord ruby-on-rails insert has-many

6
推荐指数
1
解决办法
4280
查看次数