Tag: insert

使用PostgreSQL使用ActiveRecord准备和执行语句

我试图通过使用ActiveRecord的预准备语句插入值。 但是,每次我尝试: conn = ActiveRecord::Base.connection conn.prepare “SELECT * from sampletable where id = $1” conn.execute 3 在第二个陈述之后,我得到: NoMethodError: undefined method `prepare’ for # 我该怎么办? 我正在运行Rails 3.2.1和Ruby 1.9.2 更新: 我解决了这个问题。 感谢您的回复,但它对PostgreSQL无效。 这样做的方法是: stmt = “SELECT * from sampletable where id = $1 and name = $2” values = [ { value: 1}, { value: “henry” } […]

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

我有三个型号: class Coupon :destroy has_many :events, :through => :coupon_events end class Event :destroy has_many :coupons, :through => :coupon_events end class CouponEvent < ActiveRecord::Base belongs_to :coupon belongs_to :event end 我通读了一个CSV文件来创建优惠券和coupon_events。 这非常低效,因为记录一次创建一个并导致多个查询,每个查询包括两个插入语句。 我想使用这样的单个插入查询: coupon_string = ” (‘abc’,’AAA’), (‘123′,’BBB’)” Coupon.connection.insert(“INSERT INTO coupons (code, name) VALUES”+coupon_string) 然后我需要为CouponEvent模型创建第二个插入查询,但我需要一个返回的coupon_ids列表。 是否有内置方法在插入时检索ID?