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

查看:233
本文介绍了我怎么能知道何时"刷新" 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被访问后,国家一直非活动即使用户被激活。

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.

在你上面的code,用户的对象是从数据库中读取数据存储器由 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天全站免登陆