@janeeats on code and design

Howdy

Normalizing Data in Rails Forms for Beginners - Part 2

| Comments

This post, part two of two, explains some customizations I included in a basic form for creating and editing groups on my team’s app, Jane’s Lunch. In my previous post, part one, I explained how I installed a timepicker for the groups form. In this post, I explain how I created a custom form helper to normalize the states input for user addresses.

Jane’s Lunch is built on the Ordr.In API, which requires the two-letter, state abbreviation for delivery addresses. To ensure that the data we received from the group form would be clean and play well with the Ordr.In API, I used a custom form helper that would normalize the states input for group addresses.

I put the following code in the Group helper file:

def us_states
[
  ['Alabama', 'AL'],
  ['Alaska', 'AK'],
  ['Arizona', 'AZ'],
  ['Arkansas', 'AR'],
  ['California', 'CA'],
  ['Colorado', 'CO'],
  ['Connecticut', 'CT'],
  ['Delaware', 'DE'],
  ['District of Columbia', 'DC'],
  ['Florida', 'FL'],
  ['Georgia', 'GA'],
  ['Hawaii', 'HI'],
  ['Idaho', 'ID'],
  ['Illinois', 'IL'],
  ['Indiana', 'IN'],
  ['Iowa', 'IA'],
  ['Kansas', 'KS'],
  ['Kentucky', 'KY'],
  ['Louisiana', 'LA'],
  ['Maine', 'ME'],
  ['Maryland', 'MD'],
  ['Massachusetts', 'MA'],
  ['Michigan', 'MI'],
  ['Minnesota', 'MN'],
  ['Mississippi', 'MS'],
  ['Missouri', 'MO'],
  ['Montana', 'MT'],
  ['Nebraska', 'NE'],
  ['Nevada', 'NV'],
  ['New Hampshire', 'NH'],
  ['New Jersey', 'NJ'],
  ['New Mexico', 'NM'],
  ['New York', 'NY'],
  ['North Carolina', 'NC'],
  ['North Dakota', 'ND'],
  ['Ohio', 'OH'],
  ['Oklahoma', 'OK'],
  ['Oregon', 'OR'],
  ['Pennsylvania', 'PA'],
  ['Puerto Rico', 'PR'],
  ['Rhode Island', 'RI'],
  ['South Carolina', 'SC'],
  ['South Dakota', 'SD'],
  ['Tennessee', 'TN'],
  ['Texas', 'TX'],
  ['Utah', 'UT'],
  ['Vermont', 'VT'],
  ['Virginia', 'VA'],
  ['Washington', 'WA'],
  ['West Virginia', 'WV'],
  ['Wisconsin', 'WI'],
  ['Wyoming', 'WY']
]
end

My Group helper file is located in janeslunch/app/helpers/group_helper.rb. This helper method should actually be moved to the Application helper file so that it may be used throughout this US states helper method may be used throughout the application.

Then in the view for the group form, I added this form helper to call the us_states helper:

<%= f.label(:state) %>
<%= f.select :state, us_states%>

In the select helper tag above, I’m passing in, as an argument, the us_states Group helper method, which returns the array of all the states and their abbreviations. The array of states gets passed to the select helper tag as the options for the state select field.

On the frontend, the states are spelled out in the input dropdown: Form Helper Example

In the database, the states data is saved in the format that the Ordr.in API likes: Form Helper Example

Resources:

Comments