3

I am trying to save an array of strings in a column of my table users. I have this line in my migration file add_column :users, :choices, :string. This doesn't work as I am trying to store an array and not just a string, my terminal shows Unpermitted parameter: :choices. How can I store an array ?? (Obviously add_column :users, :choices, :array doesn't work.)

3
  • 3
    wouldn't it be easier to add in a table for choices and include a foreign_key/join to the users table? this would act like an array, but work with all databases Commented Jan 25, 2022 at 16:51
  • 1
    You can store an array of text at least in Postgres. What's your database version and Rails version? Are you able to use json if creating a new table doesn't suit you? Commented Jan 25, 2022 at 16:54
  • Using (PostgreSQL) 9.6.24 and Rails 6.0.4. Basically I am receiving this array from a multiple choice question in a form and it's linked to a User. Commented Jan 25, 2022 at 17:08

2 Answers 2

3

The database column really has nothing to do with the error. You define array columns by defining a type and using the array: true option as arrays are typed in most databases unlike in Ruby:

add_column :users, :choices, :string, array: true

However this is usually a bad idea as you're violating first normal form (1NF) by putting multiple values in one column and giving up all the advantages that having a discrete table has in terms of normalization, assocations, foreign keys etc. This is idea that everyone entertains when they discover array columns - but is not really a good design decision.

Unpermitted parameter: :choices is raised when you pass an ActionController::Parameters instance with an unpermitted key. It has absolutely nothing to do with the underlying database column or the attribute.

You can whitelist array columns by passing a hash key with an empty array:

params.require(:user)
      .permit(:foo, :bar, choices: [])

This permits an array containing any type of permitted scalar value.

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

Comments

0

Should be as simple as this in your migration

  def change
    add_column :users, :choices, :string, array: true
  end

Then you probaly want to prevent writing non-array types.

#app/models/users.rb

  def choices=(input)
    raise TypeError, 'choices must be an array' unless input.is_a?(Array)
    super
  end

Comments

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.