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.
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:
2 | class 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!
07 | @user = User.find(params[ :id ]) |
10 | @user = User. new (params[ :user ]) |
14 | render :action => 'new' |
18 | @user = User.find(params[ :id ]) |
19 | if @user .update(params[ :user ]) |
22 | render :action => 'edit' |
Our base form is exactly what is generated by the Rails scaffolding:
02 | <%= form_for( @user ) do |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| %> |
18 | <%= f.text_field :email %> |
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.
02 | class User < ActiveRecord::Base |
05 | accepts_nested_attributes_for :address |
08 | class Address < ActiveRecord::Base |
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_for
adds a writer method _attributes
to the model that allows you to write code like this:
3 | user.update( :email => 'new@example.com' ) |
5 | user.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:
3 | <%= f.fields_for :address do |ff| %> |
6 | <%= ff.text_field :city %> |
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:
04 | user.address ||= Address. new |
09 | <%= form_for(setup_user(user)) do |f| %> |
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.
02 | class Task < ActiveRecord::Base |
04 | validates_presence_of :name |
07 | class User < ActiveRecord::Base |
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.
03 | <%= f.fields_for :tasks do |ff| %> |
06 | <%= ff.text_field :name %> |
07 | <% if ff.object.persisted? %> |
08 | <%= ff.check_box :_destroy %> |
09 | <%= ff.label :_destroy, "Destroy" %> |
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.
5 | 3 .times { user.tasks.build } |
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_blank
shortcut like we have above, which is equivalent to:
1 | accepts_nested_attributes_for :tasks , |
2 | :reject_if => proc {|attributes| |
3 | attributes.all? {|k,v| v.blank?} |
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.
02 | class Interest < ActiveRecord::Base |
03 | has_many :interest_users |
04 | validates_presence_of :name |
07 | class InterestUser < ActiveRecord::Base |
12 | class User < ActiveRecord::Base |
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:
02 | <%= f.fields_for :interest_users do |ff| %> |
04 | <%= ff.check_box :_destroy, |
05 | { :checked => ff.object.persisted?}, |
08 | <%= ff.label :_destroy, ff.object.interest.name %> |
09 | <%= ff.hidden_field :interest_id %> |
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 _destroy
attribute 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.
04 | user.address ||= Address. new |
05 | (Interest.all - user.interests). each do |interest| |
06 | user.interest_users.build( :interest => interest) |
08 | user.interest_users.sort_by! {|x| x.interest.name } |
09 | user/tmp/clean-controllers.md.html |
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 that
accepts_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:
Post a Comment