【问题标题】:updating active record does not update a field with an array...why?更新活动记录不会更新带有数组的字段...为什么?
【发布时间】:2014-07-20 20:28:38
【问题描述】:

我有一个模型,其中有一个用户名字符串和一个感兴趣的字符串数组。我想做的是允许用户在单击按钮时通过将兴趣附加到当前数组来添加兴趣。但是,当我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

使用 rails 4+ 和 ruby​​ 2+ 和 PSQL

【问题讨论】:

    标签: ruby-on-rails arrays


    【解决方案1】:

    更新失败的原因是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
    

    Arrays 需要注意的事项:ActiveRecord 脏跟踪不跟踪就地更新,只有 setter 跟踪脏状态。

    有两种方法可以解决这个问题:

    1. 调用&lt;attribute&gt;_will_change!会将属性标记为脏
    2. 使用model.attribute += [new_object] 追加分配,将其标记为脏

    【讨论】:

    • @existing.update_attribute(:interests, ints) 给了我错误数量的参数错误,@existing.update_attributes(interests: ints) 仍然没有保存到数据库中。我不知道您所说的&lt;attribute&gt;_will_change!model.attribute +=[new_object] 是什么意思,您能澄清一下吗?具体来说,我不明白the ActiveRecord dirty tracking does not track in place updates, only the setter tracks dirty state. 如果您有一些我可以阅读的文档,将不胜感激。
    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多