0

I recently learned about the json datatype in Rails 5, which allows you to store a hash in a PostgreSQL database. For some reason I can't find a full list of Rails 5 datatypes. Is there any sort of datatype that similarly allows you to store an array?

Such that example_record.array_datatype => ["1", "2", "3"]

4
  • 2
    "For some reason I can't find a full list of Rails 5 datatypes" -- Really?? This is the first result from a google search. Commented Jun 7, 2017 at 14:04
  • 2
    And here is the full list of supported datatypes in rails 5, as of today. Commented Jun 7, 2017 at 14:05
  • 2
    You can also check rails guides Commented Jun 7, 2017 at 14:05
  • @TomLord Thanks for the updated list, I saw that Google result but it's an incomplete list. Commented Jun 7, 2017 at 15:15

1 Answer 1

2

Yes indeed. Here is a sample migration to add an integer and a string array to a model:

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

For arrays of strings, use :text as the type.

I'd strongly recommend using an empty array instead of a null to indicate "no data", and this migration ensures that.

Sign up to request clarification or add additional context in comments.

3 Comments

What does null: false do? It makes empty arrays instead of null ones?
@JoeMorano It adds a database constraint. As with your original question, google is your friend.
Yes, it means that you cannot store a null in that column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.