我正试图弄清楚如何用rails中的嵌套资源切换"完成"操作。无论出于什么原因,我都无法让它做我想做的事。我一直收到"找不到没有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_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
资源中拥有这些完成/未完成的路由,如下所示:
resources :lists do
resources :books do
member do
put :finish
put :unfinish
end
end
end
然后调整您的link_to
调用以发送:finish_list_book_path(@list, book)
和未完成的等效调用。