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