2017-06-07 27 views
-2

我最近了解到Rails 5中的json數據類型,它允許您在PostgreSQL數據庫中存儲散列。出於某種原因,我找不到Rails 5數據類型的完整列表。有沒有類似的數據類型允許你存儲數組?Rails屬性可以是一個數組嗎?

這樣example_record.array_datatype => ["1", "2", "3"]

+2

*「出於某種原因,我找不到Rails 5數據類型的完整列表」* - 真的嗎? [這是谷歌搜索的第一個結果](https://stackoverflow.com/a/17918118/1954610)。 –

+2

並且[這是完整列表](https://github.com/rails/rails/blob/2b96d5822bfe407be7589e293f3265c0c7a6726c/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L73-L114)在rails 5中支持的數據類型,今天的。 –

+2

您還可以查看[導軌指南](http://edgeguides.rubyonrails.org/active_record_postgresql.html#array) – Gerry

回答

1

確實是這樣。下面是一個示例遷移到一個整數和一個字符串數組添加到模型:

class AddToBooks < ActiveRecord::Migration 
    def change 
    add_column :books, :category_ids, :integer, array: true, default: [], null: false 
    add_column :books, :subjects , :text , array: true, default: [], null: false 
    end 
end 

對於字符串的陣列,使用:text作爲類型。

我強烈建議使用空數組而不是空指示「無數據」,並且此遷移可確保。

+0

什麼'null:false'呢?它使空數組而不是空數組? –

+0

@JoeMorano它增加了一個數據庫約束。與你原來的問題一樣,谷歌是你的朋友。 –

+0

是的,這意味着您不能在該列中存儲空值。 –

相關問題