我想有一个"Customer
“模型,有一个普通的主键和另一个列来存储自定义的”客户编号“。此外,我希望db处理默认的客户编号。我认为,定义一个序列是最好的方法。我使用PostgreSQL。看看我的迁移:
class CreateAccountsCustomers < ActiveRecord::Migration
def up
say "Creating sequenze for customer number starting at 1002"
execute 'CREATE SEQUENCE customer_no_seq START 1002;'
create_table :accounts_customers do |t|
t.string :type
t.integer :customer_no, :unique => true
t.integer :salutation, :limit => 1
t.string :cp_name_1
t.string :cp_name_2
t.string :cp_name_3
t.string :cp_name_4
t.string :name_first, :limit => 55
t.string :name_last, :limit => 55
t.timestamps
end
say "Adding NEXTVAL('customer_no_seq') to column cust_id"
execute "ALTER TABLE accounts_customers ALTER COLUMN customer_no SET DEFAULT NEXTVAL('customer_no_seq');"
end
def down
drop_table :accounts_customers
execute 'DROP SEQUENCE IF EXISTS customer_no_seq;'
end
end
如果你知道一个更好的“类似rails”的方法来添加序列,让我知道会很棒。
现在,如果我做像这样的事情
cust = Accounts::Customer.new
cust.save
字段customer_no
没有预先填充序列的下一个值(应该是1002)。
你知道集成序列的好方法吗?或者有没有好的插件?为所有答案干杯!
https://stackoverflow.com/questions/7606994
复制相似问题