3

How can I achieve a nested rails form? Im having trouble getting this setup properly. Right now I have:

<%= simple_form_for @user do |f| %>

  <%= f.input :city %>
  <%= f.input :address %>
  <%= f.input :zipcode %>
  <%= f.association :interests, :as => :check_boxes, :label => false %>
  <%= f.association :holidays, :as => :check_boxes, :label => false %>

  <%= f.simple_fields_for :friend_birthdays do |friend_birthday| %>
    <%= f.input :name %>
    <%= f.input :gender, :collection => ['male','female'] %>
  <% end %>
  <%= f.button :submit %>
<% end %>

f.association is working fine for my interests & holidays models as they only need to collect a single attribute each. However, the friend_birthdays model has the same exact relationship as (interests & holidays) with the user model but requires multiple attributes to be edited/added. Any ideas?

1 Answer 1

4

If you are using Rails 3+, then it handles nested forms without any additional gems. The key is in using the "accepts_nested_attributes_for" method on the associations in your model, and the fields_for method on the form helper. Read up on them here and here.

I've never used simple_form, but I believe it drove the nested form development in Rails. So, taking a guess, you need to write your nested form references as:

<%= f.simple_fields_for :friend_birthdays do |friend_birthday| %>
  <%= friend_birthday.input :name %>
  <%= friend_birthday.input :gender, :collection => ['male','female'] %>
<% end %>

The point being, you need to call the helpers on the nested form, not the parent form.

Sign up to request clarification or add additional context in comments.

2 Comments

great thanks.. What do i add to my controller to make this work?
The controller corresponds to the parent model in this nesting, so that create/update action would call create/update on the parent model. The accepts_nested_attributes_for takes care of calling create/update on the children. In your case, User.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.