Ruby on rails 更新活动记录不会使用数组更新字段…为什么?

Ruby on rails 更新活动记录不会使用数组更新字段…为什么?,ruby-on-rails,arrays,Ruby On Rails,Arrays,我有一个模型,其中有一个用户名字符串和一个兴趣字符串数组。我想做的是允许用户在单击按钮时通过将兴趣添加到当前数组来添加兴趣。但是,当Iupdate时,它不会更新模型中的数组字段。为什么呢 例如,如果您在rails控制台中 @existing = User.find(1) ints = @existing.interests ints.append("a new interest") @existing.update(interests: ints) 这不会更新记录,我也不明白为什么…我在数据

我有一个模型,其中有一个用户名字符串和一个兴趣字符串数组。我想做的是允许用户在单击按钮时通过将兴趣添加到当前数组来添加兴趣。但是,当I
update
时,它不会更新模型中的数组字段。为什么呢

例如,如果您在rails控制台中

@existing = User.find(1)
ints = @existing.interests
ints.append("a new interest")
@existing.update(interests: ints) 
这不会更新记录,我也不明白为什么…我在数据库中看到它说Begin,Commit,True,但当我执行
User.find(1)
时,它只显示数组,没有添加新的兴趣

以下是模式:

create_table "users", force: true do |t|
   t.string   "email"
   t.string   "interests", default: [], array: true
   t.datetime "created_at"
   t.datetime "updated_at"
end
这是迁移

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :interests, array: true, default: '{}'

      t.timestamps
    end
  end
end
class CreateUsers

使用rails 4+和ruby 2+以及PSQL,更新失败的原因是使用不当。它需要您要更新的模型的id,然后是属性的哈希。您想使用
Model\update\u属性
Model\update\u属性

@existing.update_attributes(interests: ints) # Takes a hash of attributes
# or
@existing.update_attribute(:interests, ints) # takes the name of the column, and the new value
使用数组需要注意的事项:ActiveRecord脏跟踪不跟踪就地更新,只有setter跟踪脏状态

有两个选项可以解决此问题:

  • 呼叫
    \u将改变将属性标记为脏
  • 使用
    model.attribute+=[new\u object]
    添加到分配中,将其标记为脏

  • @existing.update\u attribute(:interests,ints)
    给了我一个错误数量的参数错误,
    @existing.update\u attributes(interests:ints)
    仍然无法保存到数据库中。我不知道你所说的“代码”是什么意思,你会改变的
    model.attribute+=[新对象]
    你能澄清一下吗?具体地说,我不理解
    ActiveRecord脏跟踪不跟踪就地更新,只有setter跟踪脏状态。
    如果您有一些我可以阅读的文档,我将不胜感激。