Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

ruby - How can I know when to "refresh" my model object in 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"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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 = "[email protected]" 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...