Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/silverlight/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在模型中将属性设置为数组?_Ruby On Rails_Arrays_Model_Attributes_Migrate - Fatal编程技术网

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

Ruby on rails 如何在模型中将属性设置为数组?,ruby-on-rails,arrays,model,attributes,migrate,Ruby On Rails,Arrays,Model,Attributes,Migrate,你能教我如何在模型中设置数组的属性吗 我已经试过了,但是当我使用数组的方法,比如push,each,我得到了错误未定义的方法“push”,用于nil:NilClass 我的迁移看起来像这样: class CreateContacts < ActiveRecord::Migration def change create_table :contacts do |t| t.string :name t.string :email t.string

你能教我如何在模型中设置数组的属性吗

我已经试过了,但是当我使用数组的方法,比如
push
each
,我得到了错误
未定义的方法“push”,用于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
class CreateContacts

我想将属性
city\u id
设置为Array。

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

  t.integer :city_ids, array: true, default: []
或者,您需要在尝试使用它之前为它指定一个值:

c = City.find(...)

c.city_ids ||= []

c.city_ids.push(...)

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

  t.integer :city_ids, array: true, default: []
或者,您需要在尝试使用它之前为它指定一个值:

c = City.find(...)

c.city_ids ||= []

c.city_ids.push(...)

在与模型上的数组(或其他可变值)交互时需要注意的一件重要事情。ActiveRecord当前不跟踪“破坏性”更改或就地更改。其中包括数组推送和弹出、提前更新日期时间对象。 范例


reference-

与模型上的数组(或其他可变值)交互时需要注意的一件重要事情。ActiveRecord当前不跟踪“破坏性”更改或就地更改。其中包括数组推送和弹出、提前更新日期时间对象。 范例


reference-

您是否选中了此项谢谢,但它仍然不适用于我,我无法在设置为数组的属性中使用数组方法谢谢您选中此项,但它仍然不适用于我,我无法在设置为数组的属性中使用数组方法我将该数组属性用于多个复选框,我有一些复选框,当它被选中时,数组属性将向中添加值。但我仍然不能使用像“push,first,last”这样的数组方法,因为NomethoderRor我将该数组属性用于多个复选框,我有一些复选框,当它被选中时,数组属性将向中添加值。但我仍然不能使用像“push,first,last”这样的数组方法,因为NoMethodError