我怎么知道什么时候“刷新"?我在 Rails 中的模型对象? [英] How can I know when to "refresh" my model object in Rails?

查看:23
本文介绍了我怎么知道什么时候“刷新"?我在 Rails 中的模型对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在进行的集成测试的一部分:

Here's part of an integration test that I'm having:

user = User.first
assert !user.is_active?

get confirm_email_user_url(user),:confirmId => user.mail_confirmation_hash

assert_equal response.status,200
# because confirm_email_user_url modifies the activation state of the object
user = User.first
assert_equal user.state,"activated"

我花了最后一个小时来调试这个:).在我的初始版本中,在访问 confirm_email_user_url 后我没有重新初始化 user,并且即使用户被激活,状态也始终是 inactive.

I spent the last hour debugging this :). In my initial version, I wasn't reinitializing user after confirm_email_user_url was accessed, and the state was always inactive even though the user was activated.

我怎么知道我是否应该重新加载"(缺少更好的名称)我的模型对象?我应该打电话给什么?

How do I know if I should "reload" ( lacking of a better name ) my model object? What should I call in order to do so?

推荐答案

你需要调用 user.reload 每当数据库中的数据发生变化时.

You'd need to call user.reload whenever the data has changed in the database.

在上面的代码中,用户"对象是根据User.first 从数据库获取的数据在内存中创建的.然后,看起来您的confirm_email_user_url 修改了数据库.在您重新加载它之前,对象不知道这一点,它从数据库中重新获取数据.

In your above code, the "user" object is created in memory from the data fetched from the database by User.first. Then, it looks like your confirm_email_user_url modifies the database. The object doesn't know about this until you reload it, which re-acquires the data from the database.

我不确定是否有一种编程方式可以知道您何时需要重新加载对象,但作为开发人员,您应该了解正在发生的事情并进行适当的处​​理.根据我的大部分经验(有些有限),这只是测试期间的问题.在生产中,对象加载到内存中时在数据库中进行修改的情况并不常见.通常发生的事情是修改内存中的对象,然后将其保存到数据库中(即,user.email = "foo@bar.com" 后跟 user.save).我想如果您有一个活动频繁的应用程序,其中许多用户可能会在短时间内连续修改某些内容,那么您需要小心处理.

I'm not sure if there's a programmatic way to know when you will need to reload the object, but as a developer you should be aware of what is going on and handle appropriately. In most of my experience (which is somewhat limited), this is only an issue during testing. In production, it's not typical for an object to be modified in the database while it is loaded in memory. What usually happens is the object in memory is modified and then saved to the database (i.e., user.email = "foo@bar.com" followed by user.save). I suppose if you had a high-activity application where lots of users might be modifying something in short succession, you would want to be careful about it.

这篇关于我怎么知道什么时候“刷新"?我在 Rails 中的模型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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