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

Hia*_*nho 18 ruby-on-rails rails-models rails-migrations rails-postgresql ruby-on-rails-3.1

我想要一个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
Run Code Online (Sandbox Code Playgroud)

如果您知道更好的"类似轨道"的方法来添加序列,那么让我知道真棒.

现在,如果我做了类似的事情

cust = Accounts::Customer.new
cust.save
Run Code Online (Sandbox Code Playgroud)

该字段customer_no未预先填充序列的下一个值(应为1002).

你知道整合序列的好方法吗?还是有一个好的插件?为所有答案干杯!

rob*_*les 11

我没有建议处理自定义序列的更多"轨道方式",但我可以告诉您为什么在保存后不会填充customer_no字段.

当ActiveRecord保存新记录时,SQL语句将只返回新记录的ID,而不是其所有字段,您可以在此处查看当前rails源中发生这种情况的位置https://github.com/rails/rails/ BLOB/cf013a62686b5156336d57d57cb12e9e17b5d462/ActiveRecord的/ lib目录/ active_record/persistence.rb#L313

为了查看重新加载对象所需的值...

cust = Accounts::Customer.new
cust.save
cust.reload
Run Code Online (Sandbox Code Playgroud)

如果您总是想这样做,请考虑在模型类中添加一个after_create挂钩...

class Accounts::Customer < ActiveRecord::Base
  after_create :reload
end
Run Code Online (Sandbox Code Playgroud)