bigpotato
bigpotato

Reputation: 27497

Rails + Postgres: How to select count of how many records are updated or inserted?

So I have an update statement:

UPDATE billing_infos set card_number = ''
FROM orders
WHERE billing_infos.order_id = orders.id ...);`

How would I find the count of how many records are updated by this statement?

I'm doing this in my console through ActiveRecord::Base.connection.execute() so it's just returning a <PG::Result:0x007f9c99ef0370> object.

Anyone know how I could do this using SQL or a Rails method?

Upvotes: 2

Views: 1639

Answers (3)

WiredIn
WiredIn

Reputation: 4227

As mentioned in a comment of another answer, the easiest way is to use the cmd_tuples attribute of the result

result = ActiveRecord::Base.connection.execute("insert into tbl select 'test' col")
puts result.cmd_tuples

result

1

Upvotes: 0

user80168
user80168

Reputation:

While solution showed by Vimsha will definitely work, there is also another solution (assuming you use recent enough pg), which could be a bit nicer:

with u as (
    update ... returning 1
)
select count(*) from u;

That's one query, and it's technically a select, so you run it as any other select.

Upvotes: 1

usha
usha

Reputation: 29349

p = ActiveRecord::Base.connection.execute(<query>)
p.cmd_status

This gives the command status. Something like

UPDATE 16

For more methods on PG::Result, refer here

Upvotes: 7

Related Questions