Postgresql RETURNING statement -> returning and ID after writing to a DB

Currently, I have an Articles page which creates articles in a DB.

What I would like to do is to return the ID of the submitted article.

I know how to do it with raw sql,

"INSERT INTO test (name) VALUES (‘My Name 1’) RETURNING id; "

but I was wondering if there is a way to do it, “The Rails Way”.

Still very new to RoR.

On Saturday 18 September 2010, HeisenbergsUncertaintyThizz wrote:

Currently, I have an Articles page which creates articles in a DB.

What I would like to do is to return the ID of the submitted article.

I know how to do it with raw sql,

"INSERT INTO test (name) VALUES (‘My Name 1’) RETURNING id; "

but I was wondering if there is a way to do it, “The Rails Way”.

You just do

@article = Article.create!(…)

and @article will have the correct ID. Internally, the postgresql
adapter uses RETURNING if it is supported by the PostgreSQL version (>=
8.0.2 or something).

If you’re interested in the details, read the code in /activerecord-3.0.0/lib/active_record/connection_adapters/postgresql_adapter.rb

Michael


Michael S.
mailto:[email protected]
http://www.schuerig.de/michael/

Thank you very much.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs