Fun with the simple_form Rails Gem

It’s been a long time since I sat down to write a blog about a programming related topic. I’m really hoping that changes this year, but I’ll do my best not to make promises I can’t be sure I’ll keep. I definitely hope to share more of the things I’m learning about and playing with. With that in mind, I was playing with the simple_form gem earlier today and I thought I would share the experiment that I was working on.

Often when working on a project I’ll have a few basic forms that I need for data entry within the system. Nothing too complex, just a few simple fields. For those of you who haven’t checked out simple_form yet, I highly recommend it. After getting the gem installed I created the form I needed:

<%= simple_form_for @member do |f| %>
  <%= f.input :firstname %>
  <%= f.input :lastname %>
  <%= f.input :email %>
  <%= f.input :bio %>
  <%= f.button :submit %>
<% end %>

Knowing that I would need a few more simple forms I wanted to figure out a way to be able to reuse this code snippet. Although I might not do this same approach in a large project with more complex forms I proceeded to pull out the column symbols within the snippet and came up with this:

<%= simple_form_for @member do |f| %>
  <% @member.class.column_names.each do |field| %>
    <%= f.input field.to_sym unless %w{id created_at updated_at}.include?(field) %>
  <% end %>
  <%= f.submit %>
<% end %>

This takes the @member instance variable and get its class, which in this case is Member. It looks at the column names of Member and loops through them. If the field isn’t “id”, “created_at”, or “updated_at” it creates an input field for it. This was a step closer to what I was going for. I imagine there are many opinions about this approach especially when it comes to thoughts on performance. The focus here was about experimentation. So I keep going and made some additional adjustments, caming up with this:

<%= simple_form_for form do |f| %>
  <% form.class.column_names.each do |field| %>
    <%= f.input field.to_sym unless %w{id created_at updated_at}.include?(field) %>
  <% end %>
  <%= f.submit %>
<% end %>

This allowed me to call the code as a partial like:

<%= render :partial => 'shared/form', :object => @member %>

It’s not perfect, I can’t customize the fields in any way, but it let’s me get some basic forms quickly together for testing concepts with a customer.

Anyway, that’s my recent experiment, feel free to share your thoughts and feedback.

Advertisements