So you’ve got some Rails application and you need to store information from the users across their interactions with the app. Here’s a simple, straightforward way to do that.

In your controller:

1
2
3
4
5
6
7
if params[:option]
  @option = session[:option] = params[:option]
elsif session[:option]
  @option = session[:option]
else
  @option = 'default value'
end

This checks to see if ‘option’ was passed via a parameter in the URI (e.g. /view?option=jim) or from a form. If it is, then we want to save that option in both the session, so we can access it later, as well as in a variable specifically for use in our view.

However, if params[:option] is nil but we still have it in session[:option] from some previous interaction, then we’ll set our variable @option for use in our view from the session copy.

If all else fails, then we know the user hasn’t tried to set this option in any way, and we can give it some default value.

Now, in our view:

1
2
3
4
5
<%= form_tag :action => 'view' %>
<label for="option">Choose:</label>
<%= text_field_tag 'option', @option, :size => 10 %>
<%= submit_tag 'Change' %>
</form>

This provides a simple form for our user to set the value of this option, and if the value is already set from a previous interaction with this form, then it shows up in the text field.