Rails JQUERY 切换嵌套资源

Rails JQUERY Toggle with Nested Resources

我正在尝试弄清楚如何使用 rails 中的嵌套资源切换 "finish" 操作。无论出于何种原因,我都无法让它做我想做的事。我不断收到“无法找到没有 ID 的列表”。这是有道理的,但我无法配置它以使其正常工作。很好奇是否有人知道如何配置事物以使其正常运行。我假设它可能与我的路由文件或每个块有关?在局部。谢谢。

下面的代码。

图书管理员

def finish
  @list = List.find(params[:list_id])
  @book = @list.books.find(params[:id])
  @book.update(finished: true)
    respond_to do |format|
        format.html {redirect_to list_path(@list)}
        format.js {}
    render @list
end
end

def unfinish
  @list = List.find(params[:list_id])
  @book = @list.books.find(params[:id])
  @book.update(finished: false)
    respond_to do |format|
        format.html {redirect_to list_path(@list)}
        format.js {}
    render @list
 end
end

书籍部分

 <table class="table table-hover">
<thead>
  <tr>
    <th>Title</th>
    <th>Author</th>
    <th>Pages</th>
    <th>Did you finish the book?</th>
    <th>Remove book from list</th>
  </tr>
</thead>
  <tbody>
    <% @books.each do |book| %>
      <tr>
        <td><%=book.name %></td>
        <td><%=book.author %></td>
        <td><%=book.pages %></td>
        <% if book.finished? %>
        <td class="unfinish-book"><%=link_to 'Finished',      unfinish_book_path(book), :method => :put, remote: true %></td>
    <% else %>
    <td class="finish-book"><%=link_to 'Mark as Finished', finish_book_path(book), :method => :put, remote: true %></td>
    <% end %>
    <td class><%= link_to '|Remove Book|', list_book_path(@list, book), method: :delete, data: { confirm: 'Are you sure?'} %></td>
<% end %>
  </tr>
  </tbody>
  </table>

路线

 Rails.application.routes.draw do
   root 'lists#index'

   resources :lists do
     resources :books
   end

  resources :books do
    member do
      put :finish
      put :unfinish
    end
  end
 end

如果您查看 rake routes 输出,您将看到以下 finish/unfinish 路由:

  finish_book PUT    /books/:id/finish(.:format)   books#finish
unfinish_book PUT    /books/:id/unfinish(.:format) books#unfinish

如您所见,这些 URL 中没有 :list_id 参数,只有 :id 参数,因此控制器代码中的 params[:list_id] 没有值,因此出现错误你得到了。

您可能应该在嵌套的 books 资源中包含那些 finish/unfinish 路由,如下所示:

resources :lists do
  resources :books do
    member do
      put :finish
      put :unfinish
    end
  end
end

然后调整您的 link_to 调用以发送:finish_list_book_path(@list, book) 和未完成的等效项。