我试图找出如何切换"完成"在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
答案 0 :(得分:1)
如果您查看rake routes
输出,那么您将看到以下完成/未完成路线:
finish_book PUT /books/:id/finish(.:format) books#finish
unfinish_book PUT /books/:id/unfinish(.:format) books#unfinish
正如您所看到的那样,这些网址中没有:list_id
参数,只有:id
参数,因此控制器代码中的params[:list_id]
将没有任何值,因此出现错误&# 39;重新获得。
您应该在嵌套的books
资源中包含那些完成/未完成路由,如下所示:
resources :lists do
resources :books do
member do
put :finish
put :unfinish
end
end
end
然后调整您的link_to
来电,以发送:finish_list_book_path(@list, book)
和未完成的等效广告。