我正在尝试为 Rails 中的模型使用默认值。我见过的最好的记录方式是在迁移中使用 :default 参数。但是,看起来这只适用于值。我正在尝试设置默认表达式,特别是 currval('customers_id_seq'::regclass)
。我可以手动添加默认表达式,但我不知道如何告诉 Rails 使用默认值。创建模型对象时如何使用此默认值?
编辑 这是一个更具体的例子:
class CreateTestmodels < ActiveRecord::Migration
def up
create_table :testmodels do |t|
t.integer :idxfield, :null=>false
t.string :datafield
t.timestamps
end
execute("ALTER TABLE testmodels ALTER COLUMN idxfield SET DEFAULT currval('testmodels_id_seq'::regclass)")
end
def down
drop_table :testmodels
end
end
通过此迁移,我可以运行 insert into testmodels (datafield) VALUES ('sometestdata');
,这将在表中添加一行,其中 idxfield
默认为id
.
但是,如果我从 Rails 控制台运行 Testmodel.create(:datafield=>"testdata")
,它会将 null 替换为 idxfield
并抛出异常。
最佳答案
对于现在遇到此问题的任何人,您可以通过将表达式包装在 lambda 中来在默认值迁移中使用表达式:https://github.com/rails/rails/pull/20005
例如
create_table :posts do |t|
t.datetime :published_at, default: -> { 'NOW()' }
end
关于ruby-on-rails - 如何在 ActiveRecord 中使用默认的 sql 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7492807/