thank_you
thank_you

Reputation: 11107

Array field not being recognized as attribute

I have the following model I created,

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :password_digest
      t.string :location_type
      t.integer :location_id
      t.integer :categories, array: true, default: '{}'

      t.timestamps
    end
    add_index :user, :email, unique: true
  end
end

I've also added the pg array parser gem to my Gemfile.

The issue is that whenever I create a user, it tells me that categories is an unknown attribute.

User.create(name: "Bob", email: "[email protected]", 
password: "password", password_confirmation: "password", categories: [1, 2])

The Error:

unknown attribute: categories

What's wrong and how can I fix this?

Update:

After running rake db:drop db:create db:migrate I came across this new error.

PG::Error: ERROR:  column "categories" is of type integer[] but default expression is of type integer
HINT:  You will need to rewrite or cast the expression.

Upvotes: 3

Views: 1060

Answers (1)

mu is too short
mu is too short

Reputation: 434685

The postgres_ext gem for adding array support to Rails3 understands that default: '{}' means that the SQL should say '{}'::integer[] but I'm guessing that the Rails4 driver is getting a little confused and saying '{}'.to_i or something like that; sorry, I don't have Rails4 set up anywhere so I can't be more specific but it does match the error you're seeing.

You could try using a Ruby array instead of the PostgreSQL-style array-string:

t.integer :categories, array: true, default: []

That will trigger the right to-sql-ification with postgres_ext so it should do the Right Thing in Rails4 too.

Upvotes: 6

Related Questions