Tuesday, February 26, 2013

Complex Rails Forms with Nested Attributes

Rails provides a powerful mechanism for easily creating rich forms called “nested attributes.” It allows you to combine more than one model in your forms while keeping the same basic code pattern that you use with simple single model forms.
In this article I’ll be showing a number of different ways to use this technique. I’ll assume that you’re familiar with basic Rails forms, of the kind that are generated by the scaffolding commands. We’ll be building up a complex form step by step that allows a user to edit their preferences. Our domain is a not-for-profit management system, where volunteers (users) have areas of expertise and tasks that have been assigned to them.

The Base Form

Let’s start with a basic form that can edit a user. I assume you are familiar with this pattern, so I won’t explain it. I only present it here because the rest of the article will be building on top of this code.
First up is a simple user model with just one attribute:
1# app/models/user.rb
2class User < ActiveRecord::Base
3  validates_presence_of :email
We will be using the same controller for the entire of this article. This is the beauty of nested attributes—we don’t have to change our controller code!
01# app/controllers/users_controller.rb
02class UsersController
03  def new
04    @user = User.new
05  end
06  def edit
07    @user = User.find(params[:id])
08  end
09  def create
10    @user = User.new(params[:user])
11    if @user.save
12      redirect_to @user
13    else
14      render :action => 'new'
15    end
16  end
17  def update
18    @user = User.find(params[:id])
19    if @user.update(params[:user])
20      redirect_to @user
21    else
22      render :action => 'edit'
23    end
24  end
Our base form is exactly what is generated by the Rails scaffolding:
01# app/views/users/_form.html.erb
02<%= form_for(@userdo |f| %>
03  <% if @user.errors.any? %>

06        <%= pluralize(@user.errors.count, "error") %> prohibited
07        this user from being saved:
    10      <% @user.errors.full_messages.each do |msg| %>
  • <%= msg %>
  • 12      <% end %>
    15  <% end %>
    17    <%= f.label :email %>
    18    <%= f.text_field :email %>
    21    <%= f.submit %>
    23<% end %>
    With that out of the way, let’s dive in!

    Adding an Address

    We are storing a user’s address record in a separate model, but we want to be able to edit the address on the same form as other attributes of the user.
    01# app/models/user.rb
    02class User < ActiveRecord::Base
    03  # ... code from above omitted
    04  has_one :address
    05  accepts_nested_attributes_for :address
    07# app/models/address.rb
    08class Address < ActiveRecord::Base
    09  belongs_to :user
    10  validates_presence_of :city
    Note the addition of accepts_nested_attributes_for to the User model. This method allows you to modify instances of Address using the same mass-assignment facility on User that makes simple forms so trivial. accepts_nested_attributes_foradds a writer method _attributes to the model that allows you to write code like this:
    1user = User.find(1)
    2# Normal mass-assignment
    3user.update(:email => 'new@example.com')
    4# Creates or edits the address
    5user.update(:address_attributes => {:city => 'Hobart'})
    You can see how we won’t have to modify our controller code if we set up our form correctly, since to edit the address attributes you use the same #update method as you do to edit the user’s email.
    To create the form, we will use the fields_for builder method. This is a complicated method that can do many things. Rather than explain it all upfront, I will introduce some of its many behaviours through the upcoming examples.
    First of all you can pass fields_for a symbol of a relationship name and it will intuit from that relationship how it should render the fields. I know that sounds complicated, but the following code snippet should make it clearer:
    1# app/views/users/_form.html.erb
    2# ... Form code from above omitted
    3<%= f.fields_for :address do |ff| %>
    5    <%= ff.label :city %>
    6    <%= ff.text_field :city %>
    8<% end %>
    Please note the changed variable name for the fields_for block—ff rather than f. In this case for a has_one relationship, the logic is “if an address exists, show a field to edit the city attribute. Otherwise if there is no address, don’t show any fields.” Here we hit our first stumbling block: if the fields are hidden when there is no address, how do we create an address record in the first place? Since this is a view problem (do we display fields or not?), we want to solve this problem in the view layer. We do this by setting up default values for the form object in a helper:
    01# app/helpers/form_helper.rb
    02module FormHelper
    03  def setup_user(user)
    04    user.address ||= Address.new
    05    user
    06  end
    08# app/views/users/_form.html.erb
    09<%= form_for(setup_user(user)) do |f| %>
    10  ...
    Now if the user doesn’t have an address we create a new unsaved one that will be persisted when the form is submitted. Of course, if they do have address no action is needed (||= means “assign this value unless it already has a value”).
    Try this out and you’ll see that rails even correctly accumulates and displays errors for the child object. It is pretty neat.

    Adding Tasks

    A user can have many tasks assigned to them. For this example, a task simply has a name.
    01# app/models/task.rb
    02class Task < ActiveRecord::Base
    03  belongs_to :user
    04  validates_presence_of :name
    06# app/models/user.rb
    07class User < ActiveRecord::Base
    08  # ... code from above omitted
    09  has_many :tasks
    10  accepts_nested_attributes_for :tasks,
    11    :allow_destroy => true,
    12    :reject_if     => :all_blank
    There are two new options here: allow_destroy and reject_if. I’ll explain them a bit later on when they become relevant.
    As with the address, we want tasks to be assigned on the same form as editing the user. We have just set up accepts_nested_attributes_for, and there are two steps remaining: adding correct fields_for inputs, and setting up default values.
    01# app/views/users/_form.html.erb


    03<%= f.fields_for :tasks do |ff| %>
    05    <%= ff.label :name %>
    06    <%= ff.text_field :name %>
    07    <% if ff.object.persisted? %>
    08      <%= ff.check_box :_destroy %>
    09      <%= ff.label :_destroy, "Destroy" %>
    10    <% end %>
    12<% end %>
    When fields_for is given the name of a has many relationship, it iterates over every object in that collection and outputs the given fields once for each record. So for a user that has two tasks, the above code will create two text fields, one for each task.
    In addition, for each task that is persisted in the database, a check box is created that maps to the _destroy attribute. This is a special attribute that is added by theallow_destroy option. When it is set to true, the record will be deleted rather than edited. This behaviour is disabled by default, so remember to explicitly enable it if you need it.
    Note that the id of any persisted records is automatically added in a hidden field byfields_for, you don’t have to do this yourself (though if you do have to for whatever reason, fields_for is smart enough to not add it again.) View the source on the generated HTML to see for yourself.
    The form we have created will allow us to edit and delete existing tasks for the user, but there is currently no way to add new tasks since for a new user with no tasks,fields_for will see an empty relationship and render no fields. As above, we fix this by adding new default tasks to the user in the view.
    There are a number of different UI behaviours you could apply, such as using javascript to dynamically add new records as they are needed. For this example though we are going to choose a simple behaviour of adding three blank records at the end of the list that can optionally be filled in.
    1# app/helpers/form_helper.rb
    2module FormHelper
    3  def setup_user(user)
    4    # ... code from above omitted
    5    3.times { user.tasks.build }
    6    user
    7  end
    fields_for will iterate over these three records and create inputs for them. Now no matter how few or many tasks a user has, there will always be three blank text fields for new tasks to be added. There is a problem here though—if a blank task is submitted, is it a new record that is invalid (blank name) and should cause the save to fail, or was it never filled in? By default Rails assumes the former, but that is often not what is desired. This behaviour can be customized by specifying the reject_if option toaccepts_nested_attributes_for. You can pass a lambda that is evaluated for each attributes hash, returning true if it should be rejected, or you can use the :all_blankshortcut like we have above, which is equivalent to:
    1accepts_nested_attributes_for :tasks,
    2  :reject_if => proc {|attributes|
    3    attributes.all? {|k,v| v.blank?}
    4  }

    More complicated relationships

    For this application, we want users to specify which areas in our not-for-profit they are interested in helping out with, such as admin or door knocking. This is modelled with a many-to-many relationship between users and interests.
    01# app/models/interest.rb
    02class Interest < ActiveRecord::Base
    03  has_many :interest_users
    04  validates_presence_of :name
    06# app/models/interest_user.rb
    07class InterestUser < ActiveRecord::Base
    08  belongs_to :user
    09  belongs_to :interest
    11# app/models/user.rb
    12class User < ActiveRecord::Base
    13  # ... code from above omitted
    14  has_many :interest_users
    15  has_many :interests:through => :interest_users
    16  accepts_nested_attributes_for :interest_users,
    17    :allow_destroy => true
    The only extra concept added here is the allow_destroy option, which we used in the previous example. As the name implies, this allows us to destroy child records in addition to creating and editing them. Recall that by default, this behaviour is disabled, so we need to explicitly enable it.
    As before, after adding accepts_nested_attributes_for there are two more steps to adding interest check boxes to our form: setting up appropriate default values, and using fields_for to create the necessary form fields. Let’s start with the first one:
    01# app/views/users/_form.html.erb
    02<%= f.fields_for :interest_users do |ff| %>
    04    <%= ff.check_box :_destroy,
    05          {:checked => ff.object.persisted?},
    06          '0''1'
    07    %>
    08    <%= ff.label :_destroy, ff.object.interest.name %>
    09    <%= ff.hidden_field :interest_id %>
    11<% end %>
    Once again, when fields_for is given the name of a has many relationship, it iterates over every object in that collection and outputs the given fields once for each record. So for a user that has two interests, the above code will create two check boxes, one for each interest.
    We know that the allow_destroy option above allows us to send a special _destroyattribute that if true will flag the object to be deleted. The problem is that this is the inverse of the default check box behaviour: when the check box is unchecked we want_destroy to be true, and when it is checked we want to keep the record around. That is what the last two parameters to check_box do (‘0’ and ‘1’): set the checked and unchecked values respectively, flipping them from their defaults.
    While we are in that area, we also need to override the default logic that decides whether the check box is checked initially. This is what :checked => ff.object.persisted? does—if the record exists in the database, then the user has indicated they are interested in that area, so the box should be checked. Note here the use of ff.object to access the current record in the loop. You can use this method inside any form_for or fields_for to get the current object.
    I have been talking about checking whether the current record is persisted or not. When you load a user out of the database, of course all the interest records will be persisted. The problem is only those interests already selected will be shown and checked, whereas we actually need to show all interests whether or not they have been selected in the past. This is where we use our setup_user method from earlier to provide “default” new records for interests that are not persisted.
    01# app/helpers/form_helper
    02module FormHelper
    03  def setup_user(user)
    04    user.address ||= Address.new
    05    (Interest.all - user.interests).each do |interest|
    06      user.interest_users.build(:interest => interest)
    07    end
    08    user.interest_users.sort_by! {|x| x.interest.name }
    09    user/tmp/clean-controllers.md.html
    10  end
    First this code creates a new join record for all interests that the user does not currently have selected (Interest.all - user.interests), and then uses an in-place sort (sort_by!) to ensure that the check boxes are always shown in a consistent order. Without this, all the new unchecked records would be grouped at the bottom of the list.

    Parting Words

    Nested attributes is a powerful technique to quickly develop complex forms while keeping your code nice and neat. fields_for gives you a lot of flexibility and options for conforming to the nested attributes pattern—see the documentation—and you should always try to structure your forms to take advantage of the behaviour thataccepts_nested_attributes_for gives you. Going beyond this article, just a touch of javascript magic supporting dynamic creating of new nested records can make your forms really stand out.
    You can download the complete code for this article over on github to have a play around with it. Let us know how you go in the comments.

    No comments: