说我有一个名为模型交易
具有:TRANSACTION_ code
属性。
我想该属性被自动填充可能不同于 ID序列号
(例如交易与 ID = 1
可以有 TRANSACTION_ code = 1000
)。
Say I have a model called Transaction
which has a :transaction_code
attribute.
I want that attribute to be automatically filled with a sequence number which may differ from id
(e.g. Transaction with id=1
could have transaction_code=1000
).
我试图创建Postgres的序列,然后庄家对 TRANSACTION_ code
列的默认值 NEXTVAL 。
问题是,如果我不上的回报率,当我发出了一个
@ transaction.save指定任何值
的回报率,它试图做的SQL语句: @ transaction.transaction_ code
I have tried to create a sequence on postgres and then making the default value for the transaction_code
column the nextval
of that sequence.
The thing is, if I do not assign any value to @transaction.transaction_code
on RoR, when I issue a @transaction.save
on RoR, it tries to do the following SQL:
INSERT INTO交易(TRANSACTION_ code)VALUES(NULL);
这样做是建立在交易的表里,有TRANSACTION_ code为NULL,而不是计算序列的NEXTVAL和相应的列插入。因此,当我发现,如果你指定NULL给Postgres,它假设你真的想有一个默认值(我是从ORACLE具有不同的行为到来),以NULL插入该列,不管它。
What this does is create a new row on the Transactions table, with transaction_code as NULL, instead of calculating the nextval of the sequence and inserting it on the corresponding column. Thus, as I found out, if you specify NULL to postgres, it assumes you really want to insert NULL into that column, regardless of it having a default value (I'm coming from ORACLE which has a different behavior).
我接受这个任何解决方案,或者如果回报率在数据库或完成的:
I'm open to any solution on this, either if it is done on the database or on RoR:
要么是有办法排除的ActiveRecord的属性保存
或有一种方法插入前改变列的值触发
或有一种方法来生成这些序列号范围内的回报率
或任何其他方式,只要它的工作原理: - )
either there is a way to exclude attributes from ActiveRecord's
save
or there is a way to change a column's value before insert with a trigger
or there is a way to generate these sequence numbers within RoR
or any other way, as long as it works :-)
在此先感谢。
有关的那一刻,你可能会被卡住获取和分配顺序的ROR模式是这样的:
For the moment, you might be stuck fetching and assigning the sequence in your ROR model like this:
before_create :set_transaction_code_sequence
def set_transaction_code_sequence
self.transaction_code = self.class.connection.select_value("SELECT nextval('transaction_code_seq')")
end
我不particularily喜欢这个解决方案,因为我想看到直接在AR这个修正......但它确实做的伎俩。
I'm not particularily fond of this solution, since I'd like to see this corrected in AR directly... but it does do the trick.