railsでいいね機能を実装しているところなのですが、
ActionController::UrlGenerationError in Books#show
Showing /home/vagrant/work/vagrant/bookers2/app/views/books/show.html.erb where line #28 raised:
No route matches {:action=>"destroy", :book_id=>nil, :controller=>"favorites"}, missing required keys: [:book_id]
のエラーが出て進めなくなってしまいました。
indexの方と同じコードをshowに貼り付けたのですが、indexはエラーが出ないのですが、showの方がでます
show
1<td> 2 <% if @book.favorited_by?(current_user) %> 3 <li> 4 <%= link_to book_favorites_path(book), method: :delete do %> ← エラー 5 <i class="fa fa-heart" aria-hidden="true" style="color: red;"></i> 6 <%= @book.favorites.count %> いいね 7 <% end %> 8 </li> 9 <% else %> 10 <li> 11 <%= link_to book_favorites_path(book), method: :post do %> ← エラー 12 <i class="fa fa-heart-o" aria-hidden="true" style="color: red;"></i> 13 <%= @book.favorites.count %> 14 <% end %> 15 </li> 16 <% end %> 17 </td>
bookcontroller
1class BooksController < ApplicationController 2 before_action :authenticate_user! 3 4 def index 5 @user = User.find(current_user.id) 6 @book = Book.new 7 @books = Book.all 8 end 9 10 def show 11 @book_show = Book.find(params[:id]) 12 @user = User.find(@book_show.user_id) 13 @book = Book.new 14 @book_comment = BookComment.new 15 @book_commetns = BookComment.all 16 end 17 18 def create 19 @book = Book.new(book_params) 20 @book.user_id = current_user.id 21 if @book.save 22 flash[:notice] = "You have created book successfully." 23 redirect_to book_path(@book.id) 24 else 25 @user = User.find(current_user.id) 26 @books = Book.where(user_id: @user.id) 27 render 'users/show' 28 end 29 end 30 31 def edit 32 @book = Book.find(params[:id]) 33 if @book.user_id != current_user.id 34 redirect_to books_path 35 end 36 end 37 38 def update 39 @book = Book.find(params[:id]) 40 if @book.update(book_params) 41 flash[:notice] = "You have updated book successfully." 42 redirect_to book_path(@book.id) 43 else 44 render 'books/edit' 45 end 46 end 47 48 def destroy 49 @book = Book.find(params[:id]) 50 @book.destroy 51 redirect_to books_path 52 end 53 54 55 private 56 57 def book_params 58 params.require(:book).permit(:title, :body, :user_id) 59 end 60end
favoritecontroller
1class FavoritesController < ApplicationController 2 def create 3 book = Book.find(params[:book_id]) 4 favorite = current_user.favorites.new(book_id: book.id) 5 favorite.save 6 redirect_to books_path(book) 7 end 8 9 def destroy 10 book = Book.find(params[:book_id]) 11 favorites = current_user.favorites.find_by(book_id: book.id) 12 favorite.destroy 13 redirect_to books_path(book) 14 end 15end 16
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。