views:

17

answers:

1

Intro

I have an object @organization that has_many :quick_facts

Basically, I want to produce a _form for each :quick_fact but with one save button, that saves all of the quick_facts.

My two problems:

First Problem:

My quick_facts are not prepopulated with their information. They only appear as blank for each quick_fact I have.

Second Problem

A save button appears on every single form

My sad sad attempt :

- for quick_fact in @organization.quick_facts
 - fields_for :quick_facts do |f|
   = f.error_messages :header_message => FORM_ERROR_HEADER_MESSAGE, :message => FORM_ERROR_MESSAGE
   = f.label :quick_fact, 'QuickFact'
   %br/
   = f.select :quick_fact, QUICK_FACTS, {}
   %br/
   = f.submit 'save', :class => 'button'
+1  A: 

You really just want one form here, since you want to submit everything at once.

Here is what I would recommend:

Use a partial to render the label and the text option for the quick fact (if you want it to be text). You want this partial to be rendered once per quick fact, so use the :collection option on the render method to specify the collections of quick facts. Each partial will get its own local copy of whatever quickfact you are on, and a variable called quickfact_counter will also be created.

In addition, you will want to use the :locals option to pass the form to the partial as a local variable, so that you can do f.label, f.text_area

So, in conclusion, your new form will be something like this:

<% form_for @organization do |form| %>
  <%= render :partial => "partial_name", :collection => @organization.quick_facts, :locals => {:form => form} %>
  <%=form.submit 'save', :class => 'button'%>
<% end %>

Then your partial will just have

<%= form.label :quick_fact, 'QuickFact' %>
<%= form.text_field :quick_fact %>

If you wanted to get even fancier you could use a layout to render the form and have it defer to the partial, but this should be enough to get you started. Being able to pass a collection to a partial is one of my favorite Rails features.

Zachary