What I Learned Today

I am loving Justin French's Formtastic for building forms on a new Rails project. It lets me create complex nested forms with pretty simple code:

<% semantic_form_for @order do |form| %>
  <%= form.inputs :email, :sign_to %>

  <% form.inputs :for => :billing_address, :name => "Billing Address" do |address| %>
    <%= address.input :name %>
    <%= address.input :line_1 %>
    <%= address.input :line_2, :required => false %>
    <%= address.input :city %>
    <%= address.input :state_or_province, :required => false %>
    <%= address.input :country_code %>
    <%= address.input :postal_code %>
  <% end %>

  <% form.inputs :for => :shipping_address, :name => "Shipping Address" do |address| %>
    <%= address.input :name %>
    <%= address.input :line_1 %>
    <%= address.input :line_2, :required => false %>
    <%= address.input :city %>
    <%= address.input :state_or_province, :required => false %>
    <%= address.input :country_code %>
    <%= address.input :postal_code %>
  <% end %>

  <%= form.inputs :first_name, :last_name, :month, :year, 
      :type, :number, :verification_value,
      :for => :credit_card, :name => "Credit Card" %>

  <%= form.buttons %>
<% end %>

A pretty fantastic part of the above is how it works with Rails 2.3. billing_address and shipping_address are nested models on @order and are treated as such. credit_card is a separate, non-ActiveRecord-backed model, but is handled pretty seamlessly here.

Published: 20 Apr 2009