Extract nextval from sequence using activerecord in Ruby on Rails 3.2.14 / Ruby 2.0.0 / PostgreSQL 9.2.4

It should be easy. I want to get the nextval sequence ... this is not the default ... this is not the primary key ... this is not the foreign key. In rare cases, I need a serial number for a user-supplied value.

I tried the following:

@nextid = ActiveRecord::Base.connection.execute("SELECT nextval('xscrpt_id_seq')") 

and I will return:

 #<PG::Result:0x007fe668a854e8 @connection=#<PG::Connection:0x00000003aeff30>> 

And using

 @nextid[0]["nextval"] 

I can get the correct value, but this does not seem to be the correct way to solve the problem. I searched, I read "Pro Active Record", which said it was used:

 M_script.find_by_sql("SELECT nextval('xscript_id_seq')") 

but it didn’t work.

Any hints on the right path (Rails) for getting the next value from the sequence in the ROR will be greatly appreciated!

+10
source share
3 answers

I believe

 ActiveRecord::Base.connection.execute("SELECT nextval('xscrpt_id_seq')") 

- correct solution. As I said in my initial question, I checked the book "Pro Active Record", and this is their recommended solution. I'm still not quite sure how ActiveRecord creates the connection, or if I need any kind of service (for example, closing it).

ActiveRecord uses the next_sequence_number method, but it is deprecated.

+9
source

You probably want to use select_value and sequence_name :

 Xscrpt.connection.select_value("select nextval('#{Xscrpt.sequence_name}')").to_i 
+7
source

This also works:

  @seq = Smodelname.find_by_sql(" select seq_name.nextval as id from dual ")[0][:id] 
+1
source

Source: https://habr.com/ru/post/950650/


All Articles