Bel*_*lly 5 ruby activerecord ruby-on-rails ruby-on-rails-3
我正在尝试为 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。
但是,如果我Testmodel.create(:datafield=>"testdata")从 rails 控制台运行,它会替换为 nullidxfield并引发异常。
对于现在遇到此问题的任何人,您可以通过将表达式包装在 lambda 中来在默认值迁移中使用表达式: https: //github.com/rails/rails/pull/20005
例如
create_table :posts do |t|
  t.datetime :published_at, default: -> { 'NOW()' }
end
| 归档时间: | 
 | 
| 查看次数: | 682 次 | 
| 最近记录: |