simple Rails preference storage

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:

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:

<%= 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.

This entry was posted in Programming and tagged , , | Current music Post Blue by Placebo. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>