【发布时间】:2012-12-05 07:07:19
【问题描述】:
我有三个模型:
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
我通读了一个 CSV 文件以创建优惠券和优惠券_事件。这是非常低效的,因为一次创建一个记录并导致多个查询,每个查询都包括两个插入语句。
我想使用这样的单个插入查询:
coupon_string = " ('abc','AAA'), ('123','BBB')"
Coupon.connection.insert("INSERT INTO coupons (code, name) VALUES"+coupon_string)
然后我需要为 CouponEvent 模型创建第二个插入查询,但我需要返回的 coupon_id 的列表。是否有在插入时检索 ID 的内置方法?
【问题讨论】:
-
如果您想要的只是从第一次查询中获得的 ID,那么只需将返回的 ID 存储在哈希中以在插入时使用。
标签: mysql ruby-on-rails activerecord insert has-many