2012-07-22 35 views
1

我正在使用SQL(即execute)在Rails 3.2中編寫遷移,以在數據庫級別實施應用程序邏輯(外鍵,缺省值,檢查,觸發器)。原因是我需要一致的數據庫交互,以防我需要直接使用來自不同應用程序(即不是Rails)或大量導入數據的相同數據庫。除了默認值對於一個型號(見下文),一切似乎都非常出色。使用Rails中的SQL遷移更新updated_at和created_at的默認值的問題?

例如created_at將包括NOT NULL DEFAULT current_timestamp。如果我在數據庫中創建記錄,這很好,但由於某種原因,schema.rb沒有檢測到默認值,但是正確地標識了約束條件。結果是我無法使用Model.create或Model.new(例如BibliographicItem.create(title: "Foo"))在數據庫中保存實例,因爲created_atupdated_at最終爲nil,這違反了schema.rb中的null: false約束。

在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?對於我所有的其他模型,使用相似(但更簡單的定義),沒有問題。

+0

我改變了這個問題,因爲我最初並不理解這個問題的範圍...... – Torsti 2012-07-22 10:51:51

回答

0

,我發現我的問題,這正好,有沒有做SQL遷移,created_at或schema.rb的原因,但由於沒有驗證validates publication_year, numericality: { only_integer: true, less_than_or_equal_to: Date.today.year() }時PUBLICATION_YEAR是nil引起的。

Bangs head against wall。

+0

雖然我很高興Rails在自定義遷移方面表現的如此出色...... – Torsti 2012-07-22 11:07:25