新的数据没有坚持到Rails的阵列列上的Postgres [英] New data not persisting to Rails array column on Postgres

查看:120
本文介绍了新的数据没有坚持到Rails的阵列列上的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

用户模型有此方法:

The user model has this method:

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

以下规格传递,直到我加入 user.reload 呼叫后 #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的是没注意到你的朋友阵列,因为改变了,好了,底层数组引用不改变,当你:

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宝石并给出的this问题

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:

String类型的属性没有被标记为脏,当它与修改<<

String attribute isn't marked as dirty, when it changes with <<

我期望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.

这篇关于新的数据没有坚持到Rails的阵列列上的Postgres的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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