使用Ruby on Rails 3.2.14 / Ruby 2.0.0 / PostgreSQL 9.2.4中的activerecord从序列中检索nextval [英] Retrieve the nextval from a sequence using activerecord in Ruby on Rails 3.2.14 / Ruby 2.0.0 / PostgreSQL 9.2.4

查看:99
本文介绍了使用Ruby on Rails 3.2.14 / Ruby 2.0.0 / PostgreSQL 9.2.4中的activerecord从序列中检索nextval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很简单。我想检索序列的nextval ...这不是默认值...这不是主键...这不是外键。在极少数情况下,我需要一个用户提供值的序列号。

This should be SO simple. I want to retrieve the nextval of a sequence... it's not a default value... it's not a primary key... it's not a foreign key. In rare cases, I need a sequence number for a user supplied value.

我尝试了以下操作:

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

,我得到的是:

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

并通过使用

@nextid[0]["nextval"]

我可以得到正确的价值,但似乎不是解决问题的正确方法。搜索后,我读了 Pro Active Record,该词表示要使用:

I can get the correct value, but it doesn't seem like the right way to approach the problem. I've searched, I read "Pro Active Record", which said to use:

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

但是,这没用。

任何有关从ROR中的序列中检索nextval的正确(罗尔斯方法)的提示,将不胜感激!

Any hints on the "correct" (Rails way) to retrieve a nextval from a sequence in ROR, would be very appreciated!

推荐答案

我相信

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

是正确的解决方案。正如我在原始问题中所说的那样,我检查了 Pro Active Record这本书,这是他们推荐的解决方案。我仍然不确定ActiveRecord是如何建立连接的,或者是否需要维护(例如关闭连接)。

is the correct solution. As I said in my original question, I checked the book "Pro Active Record" and it is their recommended solution. I'm still not exactly sure how ActiveRecord is making the connection, or if there's any maintenance I need to do (such as closing it).

ActiveRecord曾经有一个 next_sequence_number方法,但是已经过时了。

ActiveRecord used to have a "next_sequence_number" method, but that has been deprecated.

这篇关于使用Ruby on Rails 3.2.14 / Ruby 2.0.0 / PostgreSQL 9.2.4中的activerecord从序列中检索nextval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆