Search code examples
ruby-on-railsvirtual-attribute

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 same 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?


Solution

  • 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.