【问题标题】:Problems with default values for updated_at and created_at with SQL migrations in Rails?Rails 中的 SQL 迁移时,updated_at 和 created_at 的默认值有问题吗?
【发布时间】:2012-07-22 10:13:41
【问题描述】:

我正在使用 SQL(即execute)在 Rails 3.2 中编写迁移,以在数据库级别强制执行应用程序逻辑(外键、默认值、检查、触发器)。原因是我想要一致的数据库交互,以防我需要使用来自不同应用程序(即不是 Rails)的相同数据库或直接大量导入数据。除了一个模型的默认值(见下文)之外,一切似乎都运行良好。

例如created_at 将包括NOT NULL DEFAULT current_timestamp。如果我在数据库中创建一条记录,这一切都很好,但由于某种原因,schema.rb 没有检测到默认值,而是正确识别了NOT NULL 约束。结果是我无法使用 Model.create 或 Model.new(例如 BibliographicItem.create(title: "Foo"))在数据库中保存实例,因为 created_atupdated_at 最终成为 nil,这违反了 null: false 约束在 schema.rb 中。

schema.rb 中有问题的表:

create_table "bibliographic_items", :id => false, :force => true do |t|
  t.string   "uuid",             :limit => nil, :null => false
  t.string   "title",            :limit => nil, :null => false
  t.integer  "publication_year"
  t.string   "type",             :limit => nil, :null => false
  t.text     "description"
  t.datetime "created_at",                      :null => false
  t.datetime "updated_at",                      :null => false
end

它的型号:

class BibliographicItem < ActiveRecord::Base
  include Extensions::UUID
  attr_accessible :title, :publication_year, :description

  has_many :authorships
  has_many :authors, through: :authorships, order: "role DESC, author_order DESC NULLS LAST"

  validates :title, presence: true, length: { maximum: 500 }

  validates :publication_year, numericality: { only_integer: true,
                               less_than_or_equal_to: Date.today.year() }
end

execute语句中的表创建:

CREATE TABLE bibliographic_items (
uuid uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
title varchar NOT NULL,
publication_year int CHECK (publication_year <= left(now()::text, 4)::int),
type varchar NOT NULL REFERENCES bibliographic_item_types ON UPDATE CASCADE ON DELETE RESTRICT,
description text,
created_at timestamp without time zone NOT NULL DEFAULT current_timestamp,
updated_at timestamp without time zone NOT NULL DEFAULT current_timestamp,
CHECK (updated_at >= created_at)
);

为什么.create.new 不为created_atupdated_at 赋值?对于我所有的其他模型,具有相似(但更简单的定义)没有问题。

【问题讨论】:

  • 我改变了问题,因为我最初不了解问题的范围......

标签: sql ruby-on-rails postgresql migration default


【解决方案1】:

我找到了问题的原因,它与 SQL 迁移、created_at 或 schema.rb没有任何关系,而是由于在 publication_year 为时验证 validates publication_year, numericality: { only_integer: true, less_than_or_equal_to: Date.today.year() } 失败引起的nil.

刘海撞墙。

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2014-08-17
    • 2021-11-10
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2020-06-02
    • 2016-04-05
    相关资源
    最近更新 更多