update value of virtual attribute in view is not updating model
I'm updating the value of a virtual attribute in my view but this is not being reflected in the model instance.
For example:
MyModel.erb
attr_accessor_with_default :hello_world, false
View.html.erb
<%= @mymodel.hello_world %><br/>
<%
if ( @mymodel.hello_world == false )
@mymodel.hello_world = true
end
%>
<%= @mymodel.hello_world %>
The view outputs:
false
true
However, when I reload the page the s开发者_Go百科ame output is shown, when it should be:
true
true
I am seeing the above behaviour in an edit form. When I submit the form (with validation errors) it reloads (displaying errors) but the value for hello_world is not being updated.
Do you have any suggestions? What should I do to get the desired behaviour?
Your page is working as expected. The hello_world virtual attribute is being initialized as false and then set to true. The problem is your expectation of what will happen when you refresh the page.
The refreshed page is seen as a totally new request to rails with it's own (new) copy of @mymodel. This is why your results are the same when the refresh is done as the old value of @mymodel.hello_world is lost when the new instance is created.
If you wish to avoid this you will need some mechanism to persist the value between requests. This can either be some form of persistent storage such as a database or you can use the standard mechanism for persisting temporary values between requests, namely the session.
Virtual attributes are not persistent between requests since they are just stored in the @mymodel instance and not in a session or database. Every time you refresh the page, a new instance of @mymodel is created and doesn't know anything about the virtual attributes previously assigned to it.
If it's an attribute that you want to save, you should store it in the database like a regular model attribute.
精彩评论