Search code examples
ruby-on-railsformsrouteszurb-foundationnested-resources

Rails Nested Form Object in other controller


After trying to make this work for about 12 hours now, I have to turn to SO for salvation. Here's the scenario.

I'm using zurb foundation 4, and am trying to make a reveal modal ajax form for a nested resource in my dashboard.

I have the following nested resources:

  resources :lessons, only: [:index, :edit, :show] do
    resources :notes, only: [:new, :create, :edit, :delete]
  end

form at lessons/1/notes/new works fine.

I have a table on my static_pages/home like so:

  <table>
    <thead>
    <tr>
      <th>Student</th>
      <th>Subject</th>
    </tr>
    </thead>
<% @lessons.each do |lesson| %>
    <tr>
      <td><%= link_to lesson.student.name, lesson %></td>
      <td><%= lesson.subject.name %></td>
      <td><%= link_to 'make a note', new_lesson_note_path(lesson), "data-reveal-id"=>"note-for" %></td>
    </tr>
<% end %>

Under all my markup, I have the following form in a foundation reveal modal:

<!--Reveal Form-->
<div id="note-for" class="reveal-modal">
<% @lessons.each do |lesson| %> <--form now associated with proper object-->
  <%= form_for Note.new, :url => new_lesson_note_path(lesson) do |f| %>
      <div class="field">
        <%= f.label :content %>
        <%= f.text_area :content %>
      </div>
      <div class="actions">
        <%= f.submit "Save", class: "small button"%>
      </div>
  <% end %>
  <a class="close-reveal-modal">&#215;</a>
  <% end %>
</div>

Modal renders fine, submitting the form however throws the following error:

No route matches [POST] "/lessons/1/notes/new"

I'm seriously at a loss here, please help.


Solution

  • FINALLY!

    after 13 hours of tinkering, the solution!

    add a loop within the reveal modal div

    <div id="note-for" class="reveal-modal">
       <% @lessons.each do |lesson| %>
        .......
       <% end %>
    </div>
    

    ensure notes_controller.rb action is properly formatted

      def create
        @lesson = Lesson.find(params[:lesson_id])
        @note = @lesson.notes.build(params[:note])
        if @note.save
        respond_to do |format|
          format.html { redirect_to root_path, notice: 'Lesson noted!' }
          format.js
        end
        else
          redirect_to root_path
        end
      end
    

    and now I'm off to the pub! thanks ole