小编Daw*_*een的帖子

如何在 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
查看次数

MySQL自动增量查询返回两行

我有一个带有一个主键(即自动增量列)的inno-db表。我正在使用以下查询来查找下一个自动增量ID:

SELECT Auto_increment FROM information_schema.tables WHERE table_name='mytable';
Run Code Online (Sandbox Code Playgroud)

但是,当我查看结果时,我得到两行返回两个值(1352、123841)。我尝试过重置自动增量值,甚至删除了2000以下的行。如何重置表以返回单个结果?

mysql auto-increment

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