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



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

例如,如果你在rails控制台…

@existing = User.find(1)
ints = @existing.interests
ints.append("a new interest")
@existing.update(interests: ints) 

这没有更新记录,我不明白为什么…我在我的数据库中看到它显示Begin, Commit, True,但是当我执行User.find(1)时,它只显示没有添加新兴趣的数组。

schema:

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

使用rails 4+和ruby 2+和PSQL

更新失败的原因是ActiveModel::Relation#update使用不当。它需要要更新的模型的id,然后是属性的哈希值。您想使用Model#update_attributesModel#update_attribute:

@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跟踪脏状态。

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

  1. 调用<attribute>_will_change!将属性标记为dirty
  2. 使用model.attribute += [new_object]来添加赋值,将其标记为dirty

最新更新