[英]updating active record does not update a field with an array…why?
我有一个模型,其中有一个用户名字符串和一个兴趣字符串数组。 我想做的是允许用户在单击按钮时通过将兴趣添加到当前数组来添加兴趣。 但是,当我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
更新失败的原因是因为未正确使用ActiveModel::Relation#update
。 它期望您要更新的模型的ID,然后是属性的哈希。 您要使用Model#update_attributes
或Model#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脏跟踪不会跟踪就地更新,只有设置程序会跟踪脏状态。
有两种解决方案:
<attribute>_will_change!
会将属性标记为脏 model.attribute += [new_object]
附加作业,将其标记为脏
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.