新数据未持久化到 Postgres 上的 Rails 数组列 [英] New data not persisting to Rails array column on Postgres
问题描述
我有一个带有文本类型朋友列的用户模型.运行此迁移以在 postgres 中使用数组功能:
I have a user model with a friends column of type text. This migration was ran to use the array feature with postgres:
add_column :users, :friends, :text, array: true
用户模型有这个方法:
def add_friend(target)
#target would be a value like "1234"
self.friends = [] if self.friends == nil
update_attributes friends: self.friends.push(target)
end
以下规范通过,直到我在调用 #add_friend
后添加 user.reload
:
The following spec passes until I add user.reload
after calling #add_friend
:
it "adds a friend to the list of friends" do
user = create(:user, friends: ["123","456"])
stranger = create(:user, uid: "789")
user.add_friend(stranger.uid)
user.reload #turns the spec red
user.friends.should include("789")
user.friends.should include("123")
end
这也发生在开发中.模型实例已更新并在数组中具有新的 uid,但是一旦在不同的操作中重新加载或重新加载用户,它就会恢复到调用 add_friend
方法之前的状态.
This happens in development as well. The model instance is updated and has the new uid in the array, but once reloaded or reloading the user in a different action, it reverts to what it was before the add_friend
method was called.
使用 Rails 4.0.0.rc2 和 pg 0.15.1
Using Rails 4.0.0.rc2 and pg 0.15.1
这可能是什么?
推荐答案
我怀疑 ActiveRecord 没有注意到您的 friends
数组已更改,因为底层数组引用并未更改当你:
I suspect that ActiveRecord isn't noticing that your friends
array has changed because, well, the underlying array reference doesn't change when you:
self.friends.push(target)
这将改变数组的内容,但数组本身仍然是同一个数组.我知道这个问题出现在 Rails3 中的 postgres_ext gem 并给出 这个问题:
That will alter the contents of the array but the array itself will still be the same array. I know that this problem crops up with the postgres_ext gem in Rails3 and given this issue:
当字符串属性随 <<
我希望 Rails4 的行为方式相同.
I'd expect Rails4 to behave the same way.
解决方案是创建一个新数组,而不是尝试就地修改数组:
The solution would be to create a new array rather than trying to modify the array in-place:
update_attributes friends: self.friends + [ target ]
在向现有数组添加元素的同时创建新数组的方法有很多,请使用您喜欢的任何一种.
There are lots of ways to create a new array while adding an element to an existing array, use whichever one you like.
这篇关于新数据未持久化到 Postgres 上的 Rails 数组列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!