简体   繁体   中英

How to get auto-generated row primary key via Ruby PostgreSQL gem?

My table in PostgreSQL looks like this:

CREATE TABLE user (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL
)

I'm using Ruby pg gem to add a record to the table:

c = PG.connect(dbname: 'foo')
id = c.exec_params('INSERT INTO user (name) VALUES ($1)', ['Jeff']).oid_value

I'm getting nil back, instead of the auto-generated id of the new record. What is the right way to get it back?

According to the docs , if the object id you're retrieving isn't set, thus nil.

You either have to set the object id yourself, or use returning like this:

res  = conn.exec("INSERT INTO users (name) VALUES ('john') returning id")
res[0]['id']
#=> 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM