[英]Error 400 when commenting on ruby on rails ecommerce web app
I'm actually making an ecommerce web app which has a User
, Category
, Book
and Comment
models. 我实际上正在制作一个具有User
, Category
, Book
和Comment
模型的电子商务Web应用程序。 Everything is working nice, but when I try to comment in one of the book, it gives a 400 error. 一切工作正常,但是当我尝试在其中一本书中发表评论时,出现400错误。 I really need you to help me out. 我真的需要你帮我 https://github.com/felixpro/Book-app this is my repository. https://github.com/felixpro/Book-app,这是我的存储库。
This is my CommentsController 这是我的CommentController
class CommentsController < ApplicationController
before_action :authenticate_user!
def create
book = Book.find(params[:comment][:book_id])
comment = book.comments.build(comment_params)
comment.user = current_user
if comment.save
redirect_to book_path(@book)
end
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
This is the comment view partial, 这是评论视图的一部分,
<% if signed_in? %>
<div class="card bg-light new-comment">
<div class="card-body">
<p class="font-weight-bold">Deja tu comentario:</p>
<%= form_for @book.comments.build do |f| %>
<%= f.hidden_field :book_id, value: @book.id %>
<div class="form-group">
<%= f.text_area :body, rows: 4, class: "form-control" %>
</div>
<div class="text-right">
<%= f.submit "Comentar", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
<% else %>
<div class="card bg-light mt-5">
<div class="card-body">
<p class="card-text text-center lead"><%= link_to "Regístrate", new_user_registration_path %> o <%= link_to "Ingresa", new_user_session_path %> para comentar</p>
</div>
</div>
<% end %>
Here are the routes 这是路线
Rails.application.routes.draw do
devise_for :users
root 'books#index'
resources :books
resources :comments, only: [:create]
end
The error say 错误说
The error you mentioned is linked to the fact that you have a special invisible character (non-breaking space) at line 9 and 14 in your CommentsController. 您提到的错误与以下事实有关:在CommentsController中的第9行和第14行,您有一个特殊的不可见字符(不间断空格)。 This is why you get the 这就是为什么你得到
NameError (undefined local variable or method `' for ...)
This often happens when you hit an additional key at the same time you hit the space bar (cmd + space bar on MacOS). 当您同时按下空格键(在MacOS上为cmd +空格键)的同时按下其他键时,通常会发生这种情况。 Delete those empty lines and type the enter key again to clear the character. 删除那些空行,然后再次输入Enter键以清除字符。
Then the other answer is right, you'll have have to update your book variable name. 然后,另一个答案是正确的,您必须更新书的变量名称。
You have referred to @book
when the variable is a local book
. 当变量是本地book
时,您已引用@book
。 Use @
at the beginning of the line 6: 在第6行的开头使用@
:
@book = Book.find(params[:comment][:book_id])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.