我想有一个"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)。
你知道集成序列的好方法吗?或者有没有好的插件?为所有答案干杯!
发布于 2011-09-30 15:30:02
我没有建议用更“rails的方式”来处理定制序列,但是我可以告诉你为什么在保存之后customer_no字段看起来没有被填充。
当ActiveRecord保存一条新记录时,SQL语句将只返回新记录的ID,而不是它的所有字段,您可以在https://github.com/rails/rails/blob/cf013a62686b5156336d57d57cb12e9e17b5d462/activerecord/lib/active_record/persistence.rb#L313的当前rails源代码中看到这一点。
为了查看该值,您需要重新加载对象...
cust = Accounts::Customer.new
cust.save
cust.reload
如果你总是想这样做,考虑在你的模型类中添加一个after_create钩子……
class Accounts::Customer < ActiveRecord::Base
after_create :reload
end
发布于 2012-05-24 21:56:39
我遇到了类似的问题,但我也将:null => false
放在了字段中,希望它将自动填充为nextval。
在我的例子中,如果请求中没有提供任何属性,AR仍然会尝试插入NULL
,这会导致违反非空约束的异常。
这是我的变通方法。我刚刚从@attributes
和@changed_attributes
中删除了这个属性键,在本例中postgres正确地放入了预期的序列nextval。
我把这个放入模型中:
before_save do
if (@attributes["customer_no"].nil? || @attributes["customer_no"].to_i == 0)
@attributes.delete("customer_no")
@changed_attributes.delete("customer_no")
end
end
Rails 3.2 / Postgres 9.1
发布于 2012-08-03 23:54:02
如果您使用的是PostgreSQL,请查看我编写的pg_sequencer:
https://github.com/code42/pg_sequencer
它提供了在ActiveRecord迁移中创建、删除和更改序列的数字用户线。
https://stackoverflow.com/questions/7606994
复制相似问题