我想要一个Customer
带有普通主键和另一列来存储自定义“客户编号”的“”模型。此外,我希望数据库处理默认客户编号。我认为,定义一个序列是最好的方法。我使用 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)。
你知道整合序列的好方法吗?或者有什么好的插件吗?为所有答案干杯!