Bad Hombre
Bad Hombre

Reputation: 594

Ruby on Rails - Adding arrays to column

If I have a Playlist model, how can I push arrays into a column?

#<Playlist id: 1, title: "This is a playlist", songs_ids: 1>

And want to push arrays to the songs_ids column what do I have to do?

This is how the songs_ids column look like

add_column :playlists, :songs_ids, :integer, array: true, default: []

I've tried updating the attributes and adding annother id of a song to it, but I have no luck with it either:

Playlist.find(1).update_attribute(songs_ids: [1, 2])

Upvotes: 0

Views: 822

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

If you're using Postgresql you can simply use the update_all method to update array columns in your model.

Playlist.where(id: 1).update_all(songs_ids: [1,2])

Note it won't work with Playlist.find(1)....

Using Mysql you can consider to serialize to do this you must use a string type column.

 def change
    add_column :playlists, :songs_ids, :string
  end

Then specify the attribute which to serialize in your model.

class Playlist < ActiveRecord::Base 
    serialize :songs_ids, Array 
end

Then you can test pushing any value to it.

playlist = Playlist.first
playlist.songs_ids << 1
=> [1]
playlist.save
playlist.songs_ids << 2
=> [2]
playlist.save
playlist.songs_ids
=> [1, 2]

Upvotes: 1

Related Questions