2011-10-28 31 views
9

我正在使用Rails 3.1.1和PostgreSQL 9.1以及earthdistance module。 爲了能夠正確計算不同位置之間的距離,我在branches表中設置了earth類型的列。ActiveRecord中的自定義數據庫類型

我現在遇到的問題是,使用這個表我的Rails應用程序並不瞭解地球類型,因此我在得到這個我db/schema.rb

# Could not dump table "branches" because of following StandardError 
# Unknown type 'earth' for column 'location'

這是有問題的,因爲現在我可以」從schema.rb創建我的測試數據庫。

如何將此類型添加到AR或使其忽略該列?

+1

找到了問題的答案在這裏: http://stackoverflow.com/questions/383058/rails-schema-creation-problem –

+7

這是幫助他人寫出來的答案,甚至是你自己的問題,接受。它也從沒有答案的列表中拿掉這個問題。 – Nick

回答

5

試試這個:

更改你的config/application.rb中

config.active_record.schema_format = :sql 

這將改變輸出格式本地PostgreSQL的SQL格式,schema.rb將被禁止,一個新文件生成/db/config/structure.sql

+0

我沒有試過,但rails'db:schema:load'似乎仍然在尋找'schema.rb'文件。 –

+0

看起來你不得不使用'rake db:structure:load'。 –

5

另一種情況下,有人可能會遇到這種情況是將自定義postgres類型(枚舉)插入postgresql時。如果有人這樣做,仍然想爲您的schema.rb使用Ruby,則可以將自定義數據庫類型添加到適配器的有效類型列表中。

例如,假設您有這樣的遷移,其中address_typeaddress_status

class CreateAddresses < ActiveRecord::Migration 
    def up 

    execute <<-SQL 
     CREATE TYPE address_status AS ENUM ('active', 'archived'); 
     CREATE TYPE address_type AS ENUM ('billing', 'shipping'); 
    SQL 

    create_table :customer_addresses do |t| 
     # bla bla 
     t.column :address_type, :address_type 
     t.column :status, :address_status 

     t.timestamps null: false 
    end 
    end 

    def down 
    drop_table :customer_addresses 
    execute <<-SQL 
     DROP TYPE address_type; 
     DROP TYPE address_status; 
    SQL 
    end 

end 

然後在創建初始化或添加這樣的事情你application.rb中:

  • 我檢查了PostgreSQLAdpater,因爲存在:

    我的解決方案
    # config/initializers/postres_enum_custom_types.rb 
    module ActiveRecord 
        module ConnectionAdapters 
        if const_defined?(:PostgreSQLAdapter) 
         class PostgreSQLAdapter 
         NATIVE_DATABASE_TYPES.merge!(
          address_status: { name: 'character varying' }, 
          address_type: { name: 'character varying' } 
         ) 
         end 
        end 
        end 
    end 
    

    注意事項我使用的靜態分析寶石的部分方法是加載一些AR相關性 - 特別是寶石annotate

  • 原始定義的來源is here

背景上我遇到了這樣:當這發生在我身上的軌道5.0.x中的遷移運行正常,但隨後試圖運行db:test:preparedb:reset在我的測試環境將失敗。我花了相當長的時間來跟蹤這個模式轉儲問題。

+0

這對我來說不適用於Rails 4.2.8,還有其他一些我需要使用的公式嗎? –

+0

你可以分享更多關於你遇到的錯誤的信息,也許把你的代碼放在主題中,然後看看我嗎? –

+0

我跑了你鍵入的內容,它不能在5.0.1或者 – Kasumi