ActiveRecord在更新属性后未保存 [英] ActiveRecord not saving after updating attribute

查看:84
本文介绍了ActiveRecord在更新属性后未保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这里是否有一些我不理解的东西,或者是否遇到了ActiveRecord(4.1.1)中的错误.

I'm wondering if there is something at work here that I don't understand or if I've run into a bug in ActiveRecord (4.1.1).

我有一个充满记录的数据库,其中只有一个属性,一个字段中包含一些JSON.我拿一个,尝试像这样更新它.

I have a database full of records with only one attribute, a field a bit of JSON in it. I take one and try to update it like so.

test = Submission.find(1)
test.update_attribute('json_data',similar_but_different_json(test.json_data))

让我们假设方法similar_but_different_json对该JSON进行了小幅更新.就我而言,我正在修复由于表格损坏而造成的一些数据错误.

Let's assume the method similar_but_different_json makes a small update to that JSON. In my case I'm fixing some data errors that were created by a broken form.

这样做时,我没有收到任何错误,我在控制台中显示了一个提交,但未提交任何数据,并返回了true.

When doing this, I don't get any errors, I show a commit in the console but no data submitted and get a return of true.

为了真正更新记录,我必须这样做.

In order to actually update the record I have to do this.

test = Submission.find(1)
old_json_data = test.json_data
test.json_data = ""
test.json_data = similar_but_different_json(old_json_data)
test.save

似乎正在发生的事情是ActiveRecord无法识别已进行的更改必须保存.难道这就是为什么将字段设置为空字符串然后返回JSON可以保存记录吗?

What seems to be happening is that ActiveRecord doesn't identify that a change has been made that has to be saved. Could this be why setting the field to an empty string then back to JSON allows the record to save?

推荐答案

will_change!

您还可以使用:

will_change!

You can also use:

test.json_data_will_change!   # Goes before the save.

这将告诉ActiveModel属性json_data已更改(即,它是←那里有个玩笑),并会在保存时正确更新值.

This will tell ActiveModel that the attribute, json_data, has changed (i.e. it's dirty ← there's a joke there somewhere) and will update the value properly on save.

请参见 Rails未保存属性更改以获取更多详细信息.

See Rails is not saving an attribute that is changed for some more details as well.

这篇关于ActiveRecord在更新属性后未保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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