如何在模型中将属性设置为数组?

3

您能教我如何在模型中为数组设置属性吗?

我已经尝试过,但是当我使用数组的方法,例如pusheach时,我得到了错误信息:undefined method `push' for nil:NilClass

我的迁移文件如下:

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

我想将属性city_ids设置为数组。

你有检查过这个链接吗:http://reefpoints.dockyard.com/ruby/2012/09/18/rails-4-sneak-peek-postgresql-array-support.html - Arihant Godha
谢谢,但对我来说还是不起作用,我无法在设置为数组的属性中使用数组方法。 - Yuto Yasunaga
2个回答

3

在与数组(或其他可变值)交互时,有一个重要的注意事项。 ActiveRecord 目前不会跟踪“破坏性”或原地更改。这些更改包括数组推入和弹出,以及 DateTime 对象的前进。 示例:

 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


1

你需要设置一个默认值。否则,该属性将为nil,直到你给它赋值:

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

或者,在尝试使用它之前,您需要为其赋值:
c = City.find(...)

c.city_ids ||= []

c.city_ids.push(...)

我使用那个数组属性来处理多个复选框。当某个复选框被选中时,数组属性会添加相应的值。 但是我仍然无法使用像"push, first, last"这样的数组方法,因为出现了NoMethodError错误。 - Yuto Yasunaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接