Last Updated: February 25, 2016
· matiasdim

fields_for tag [Small RoR tip #2]

If you want to create or update data from different model in a specific model form an easy way to do that is using fields_for tag.

In short fields_for allow you to use additional models in the same form.

For example if you are in an user model form and need to interact with an agent model too, then:

<%= form_for @user do |f| %>
  Username: <%= f.text_field :username %>
  Password: <%= f.text_field :password %>

  <%= fields_for @agent do |fa| %>
    Name: <%= fa.text_field :name %>
    Last name: <%= fa.text_field :last_name %>
  <% end %>

  <%= f.submit %>
<% end %>

Remember that the model @agent must also be instantiated in the controller.