我想做一个upsert.Rails还不支持这个.查询是这样的:
INSERT INTO foos (thing_id, bar_id) VALUES (1, 2)
ON CONFLICT (thing_id, bar_id) DO NOTHING
Run Code Online (Sandbox Code Playgroud)
我可以用self.class.connection.execute或轻松做到这一点exec_insert.但我也希望利用准备好的陈述.我以为我可以这样做:
thing_id = ActiveRecord::Relation::QueryAttribute.new("thing_id", thing.id, ActiveRecord::Type::Integer.new)
bar_id = ActiveRecord::Relation::QueryAttribute.new("bar_id", id, ActiveRecord::Type::Integer.new)
self.class.connection.exec_insert(<<-SQL, nil, [thing_id, bar_id])
INSERT INTO foos (thing_id, bar_id) VALUES ($1, $2)
ON CONFLICT (thing_id, bar_id) DO NOTHING
SQL
Run Code Online (Sandbox Code Playgroud)
但是当我试验这个时,似乎没有创建一个准备好的语句.
我试过这种风格:
query = <<-SQL
INSERT INTO foos (thing_id, bar_id) VALUES ($1, $2)
ON CONFLICT (thing_id, bar_id) DO NOTHING
SQL
connection = ActiveRecord::Base.connection.raw_connection
connection.prepare('some_name', query)
st = connection.exec_prepared('some_name', [ …Run Code Online (Sandbox Code Playgroud)