Railsでコメント機能を追加した際にでたエラーについて
解決したいこと
ここに解決したい内容を記載してください。
例)
Ruby on Railsで本を投稿するWebアプリにコメント機能を付ける作業の時にエラーが発生しました。
解決方法を教えて下さい。
該当するソースコード
<p><%= flash[:notice] %></p>
<div class="container">
<div class="row">
<div class="col-md-3">
<%= render'book',{ user: @book.user, book: @book_new } %>
</div>
<div class="col-md-8 offset-md-1">
<h2>Book detail</h2>
<table class="table">
<tbody>
<tr>
<td>
<%= link_to user_path(@book.user.id) do %>
<%= image_tag @book.user.get_profile_image(100,100) %><br><%= @book.user.name %>
<% end %>
</td>
<td>
<%= link_to @book.title, book_path(@book) %>
</td>
<td>
<%= @book.body %>
</td>
<% if @book.user == current_user %>
<td>
<%= link_to "Edit", edit_book_path(@book.id), class:'btn btn-sm btn-success'%>
</td>
<td>
<%= link_to "Destroy", book_path(@book.id), method: :delete, "date-confirm" => "本当に消しますか?", class:'btn btn-sm btn-danger' %>
</td>
<% end %>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div>
<p>コメント件数:<%= @book.book_comments.count %></p>
<% @book.book_comments.each do |book_comment| %>
<p><%= image_tag book_comment.user.get_profile_image(100,100) %></p>
<%= book_comment.user.name %>
<% if book_comment.user == current_user %>
<%= link_to "削除", book_comment_path(book_comment, book_comment), method: :delete %>
<% end %>
<% end %>
</div>
<div>
<%= form_with model: [@book, @book_comment] do |f| %>
<%= f.text_area :comment, rows: '5' %>
<%= f.submit "送信する" %>
<% end %>
</div>
例)
class BookCommentsController < ApplicationController
def create
book = Book.find(params[:book_id])
comment = current_user.book_comments.new(book_comment_params)
comment.book_id = book.id
comment.save
redirect_to book_path(book.id)
end
def destroy
BookComment.find(params[:id]).destroy
redirect_to book_path(params[:book_id])
end
private
def book_comment_params
params.require(:book_comment).permit(:comment)
end
end
class BooksController < ApplicationController
before_action :correct_user, only: [:edit, :update]
def create
@book = Book.new(books_params)
@book.user_id = current_user.id
if @book.save
flash[:notice] = "You have created book successfully."
redirect_to book_path(@book.id)
else
@user = current_user
@books = Book.all
render :index
end
end
def index
@books = Book.all
@book = Book.new
@user = current_user
end
def show
@book_new = Book.new
@book = Book.find(params[:id])
@book_comment = BookComment.new
end
def edit
@book = Book.find(params[:id])
end
def destroy
book = Book.find(params[:id])
book.destroy
redirect_to books_path
end
def update
@book = Book.find(params[:id])
if @book.update(books_params)
flash[:notice] = "You have updated book successfully."
redirect_to book_path(@book.id)
else
render :edit
end
end
private
def books_params
params.require(:book).permit(:title, :body)
end
def correct_user
@book = Book.find(params[:id])
@user = @book.user
redirect_to books_path unless @user == current_user
end
end
自分で試したこと
コントローラー内の変数の内容など変えたりしてみましたが、エラーが解消されません。
エラーの解消方法が分かる方、どうかよろしくお願いいたします。
0