【问题标题】:Rails Nested Form Object in other controller其他控制器中的 Rails 嵌套表单对象
【发布时间】:2013-07-20 08:27:12
【问题描述】:

在尝试完成这项工作大约 12 小时后,我不得不求助于 SO 寻求救赎。这是场景。

我正在使用 zurb Foundation 4,并试图在我的仪表板中为嵌套资源创建一个显示模式 ajax 表单。

我有以下嵌套资源:

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

在课程/1/notes/new 中的表格可以正常工作。

我的 static_pages/home 上有一个表格,如下所示:

  <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 %>

在我的所有标记下,我在基础显示模式中有以下形式:

<!--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>

模态渲染很好,但是提交表单会引发以下错误:

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

我在这里很茫然,请帮忙。

【问题讨论】:

    标签: ruby-on-rails forms routing zurb-foundation nested-resources


    【解决方案1】:

    我假设您在使用 @lessons 变量时犯了一个错误。您正在传递,模型与 url 助手的关系,而不是模型。

    为解决它尝试:

    #controller
    @lesson = Lesson.find(params[:lesson_id])
    
    #view
    ...
    <%= form_for Note.new, :url => new_lesson_note_path(@lesson) do |f| %>
    ...
    

    【讨论】:

    • 这个我真的试过了,不行。然而,好消息是我已经设法通过 。请查看编辑后的代码。现在唯一的问题是它会引发路由错误。我认为 (@lessons) 将表单与一系列课程相关联,而不仅仅是一个课程。
    • SO 有一些神奇之处。通常我会在一个问题上花费数小时。放弃。在 SO 上寻求帮助。一旦我完成输入我的问题,解决方案就会突然出现在我的脑海中。
    【解决方案2】:

    终于!

    经过 13 小时的修补,解决方案!

    在显示模式 div 中添加一个循环

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

    确保 notes_controller.rb 动作格式正确

      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
    

    现在我要去酒吧了!谢谢你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多