首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将序列添加到迁移并在模型中使用它们?

如何将序列添加到迁移并在模型中使用它们?
EN

Stack Overflow用户
提问于 2011-09-30 15:02:07
回答 3查看 7.5K关注 0票数 19

我想有一个"Customer“模型,有一个普通的主键和另一个列来存储自定义的”客户编号“。此外,我希望db处理默认的客户编号。我认为,定义一个序列是最好的方法。我使用PostgreSQL。看看我的迁移:

代码语言:javascript
复制
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”的方法来添加序列,让我知道会很棒。

现在,如果我做像这样的事情

代码语言:javascript
复制
cust = Accounts::Customer.new
cust.save

字段customer_no没有预先填充序列的下一个值(应该是1002)。

你知道集成序列的好方法吗?或者有没有好的插件?为所有答案干杯!

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7606994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档