0

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])
4
  • Possible duplicate of Rails: Adding migration to add an array (default empty) Commented Mar 29, 2017 at 17:09
  • Are you serialising the array in your model class? serialize :song_ids, Array in Playlist.rb apidock.com/rails/ActiveRecord/Base/serialize/class Commented Mar 29, 2017 at 17:15
  • @muistooshort I am using mysql database for development and postgres for production Commented Mar 29, 2017 at 17:40
  • 1
    AFAIK MySQL doesn't support array columns so your songs_ids is just an int. There are so many differences between MySQL and PostgreSQL that ActiveRecord will not help you with that developing on MySQL and deploying on PostgreSQL is madness. Develop and test with PostgreSQL if that's what you're deploying on. Rails/ActiveRecord doesn't offer any useful support for database portability beyond that absolute basics. Commented Mar 29, 2017 at 17:43

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

2 Comments

Tested in Postgresql this works, on Mysql it doesn't, this one keeps the songs_ids attribute as nil after the operation.
It doesn't work even if I serialize because as you've mentioned I think it's to do with the database, and I'm guessing that's the only workaround for this?

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.