Home How to use an array field in a database table in Ruby on Rails
Post
Cancel

How to use an array field in a database table in Ruby on Rails

In Ruby on Rails, you can use an array field in a database table by defining it as a text data type and using the array: true option in your migration.

For example, suppose you want to create a tags field in your posts table that will store an array of tags for each post. You can create this field with the following migration:

1
2
3
4
5
6
7
8
# Table: posts

id | title     | tags
---+------------+----------------
1  | My Post    | {ruby, rails}
2  | Another    | {ruby}
3  | Post       | {rails, programming}

1
2
3
4
5
class AddTagsToPosts < ActiveRecord::Migration[6.0]
  def change
    add_column :posts, :tags, :text, array: true, default: []
  end
end

Then, in your Post model, you can access the tags field as an array:

1
2
3
4
5
6
7
8
9
10
11
12
class Post < ApplicationRecord
  # ...

  def add_tag(tag)
    self.tags << tag
  end
end

post = Post.first
post.tags # => []
post.add_tag('ruby')
post.tags # => ['ruby']

You can also perform array operations on the field using Active Record’s where method. For example:

1
2
3
4
5
# Find all posts with the tag 'ruby'
Post.where('tags @> ARRAY[?]', 'ruby')

# Find all posts with the tags 'ruby' and 'rails'
Post.where('tags @> ARRAY[?, ?)', 'ruby', 'rails')

I hope this helps! Let me know if you have any questions.


This post is licensed under CC BY 4.0 by the author.