Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested rails forms with Simple Form?

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?

like image 719
js111 Avatar asked Aug 10 '26 18:08

js111


1 Answers

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.

like image 184
pduey Avatar answered Aug 12 '26 07:08

pduey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!