Rails, Ruby

Rails: Add Column Array in Database

Say we want to add a column named selected to our user model. Our selected would be an array of integers.

First, generate a migration in terminal.

rails g migration add_selected_to_user selected:array

This would be generated under db/migrate/:

class AddSelectedToUser < ActiveRecord::Migration
  def change
    add_column :users, :selected, :integer, array: true
  end
end

Add this at the end of the add_column line:

default: []

Run database migration in terminal:

rake db:migrate

Allow this parameter to be submitted, in UsersController:

params.require(:user).permit(:selected, selected: [])

This supposedly would allow you to submit an array of integers. However, if you try to submit an empty array, you’ll get this error:

Value for params[:selected] was set to nil, because it was one of [], [null] or [null, null, ...]. Go to http://guides.rubyonrails.org/security.html#unsafe-query-generation for more information.

Rails is on the lookout for empty arrays. Whenever it discovers one submitted, it pounces on it with deep_munge [1] and promptly turns it into nil. To persuade it not to, add this in config/application.rb [2]:

config.action_dispatch.perform_deep_munge = false

Now arrays can be submitted. Everyone’s happy.

Standard