3

Can you teach me how to set an attribute to Array in Model?.

I have tried it but when I use array's method like push, each, I got the error undefined method `push' for nil:NilClass

My migrate look like this:

class CreateContacts < ActiveRecord::Migration
  def change
    create_table :contacts do |t|
      t.string :name
      t.string :email
      t.string :email_confirmation
      t.integer :city_ids, array: true
      t.text :description

      t.timestamps
    end
  end
end

I would like to set attribute city_ids to Array.

2
  • have you check this one reefpoints.dockyard.com/ruby/2012/09/18/… Commented Jan 16, 2014 at 4:14
  • Thank you, but It still not work for me, I can't use array method in attribute which set to be an array Commented Jan 16, 2014 at 8:35

2 Answers 2

3

One important thing to note when interacting with array (or other mutable values) on a model. ActiveRecord does not currently track "destructive", or in place changes. These include array pushing and poping, advance-ing DateTime objects. Example

 john = User.create(:first_name => 'John', :last_name => 'Doe',
  :nicknames => ['Jack', 'Johnny'])

john = User.first

john.nicknames += ['Jackie boy']
# or
john.nicknames = john.nicknames.push('Jackie boy')
# Any time an attribute is set via `=`, ActiveRecord tracks the change
john.save

Referrence - link

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

Comments

1

You need to set a default. Otherwise, the attribute is nil, until you give it a value:

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

Or, you need to give it a value befor eyou attempt to use it:

c = City.find(...)

c.city_ids ||= []

c.city_ids.push(...)

1 Comment

I use that array attribute for multiple check box, I have some checkbox and when it checked, array attribute will add value into. But I still can't use array method like "push, first, last" because NoMethodError

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.