Topic: accepts_nested_attributes_for and fields_for not working!!

I'm trying to have one

Re: accepts_nested_attributes_for and fields_for not working!!

Sorry, it didn't post correctly. Here's the post:

I'm trying to have one "menu" object that is updated with new "brunch" "lunch" and "dinner" objects daily. Each "brunch" object has attributes "menu_id" and "brunch_menu" (a pdf uploaded to s3 via carrierwave), and same for "lunch" and "dinner" objects.  But when I do fields_for and try to save the menu object, it doesn't create or save the new "brunch" "lunch" or "dinner" objects. It sends me to the "show" page for the newly updated menu and gives the error "undefined method 'brunch_menu' for nil:nilclass". Please help!

-------------
Menu Controller:

  def edit
    @menu = Menu.find(params[:id])
    @menu.dinners.build
    @menu.lunches.build
    @menu.brunches.build
  end

--------------
Menu Model:

class Menu < ActiveRecord::Base
  has_many :brunches, :dependent => :destroy
  has_many :lunches, :dependent => :destroy
  has_many :dinners, :dependent => :destroy
  accepts_nested_attributes_for :lunches, :dinners, :brunches
end

--------------
Brunch/Lunch/Dinner Model:

class Brunch < ActiveRecord::Base
  attr_accessible :menu_id, :brunch_menu
  belongs_to :menu
  mount_uploader :brunch_menu, ImageUploader
end

-------------
Menu Form Partial:
<%= form_for @menu, :html => {:multipart => true} do |f| %>
  <% if @menu.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@menu.errors.count, "error") %> prohibited this menu from being saved:</h2>

      <ul>
      <% @menu.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
    <%= f.fields_for :brunches do |a|%>
    <div class="field">
             <%= a.label :brunch_menu %><br />
             <%= a.file_field :brunch_menu %>
    </div>
    <% end %>
   
   
    <%= f.fields_for :lunches do |b|%> 
    <div class="field">
             <%= b.label :lunch_menu %><br />
             <%= b.file_field :lunch_menu %> 
    </div>
    <% end %>
   
   
    <%= f.fields_for :dinners do |c|%> 
    <div class="field">
             <%= c.label :dinner_menu %><br />
             <%= c.file_field :dinner_menu %> 
    </div>
    <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>



THANKS SO MUCH!!!
Sarah

Re: accepts_nested_attributes_for and fields_for not working!!

You need to look very closely at your log files. All the info you need in order to debug your problem is in the stack trace. If you have difficulty with interpreting this then post the log file entries ad I'll take a look

What you want and what you need are too often not the same thing!
When your head is hurting from trying to solve a problem, stop standing on it. When you are the right way up you will see the problem differently and you just might find the solution.
(Quote by me 15th July 2009)