新数据未保存到 Postgres 上的 Rails 数组列 [英] New data not persisting to Rails array column on Postgres

查看:33
本文介绍了新数据未保存到 Postgres 上的 Rails 数组列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户模型,其中包含文本类型的朋友列.运行此迁移以将数组功能与 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆