1
我对Rails相当陌生,而且我正在关注一个在线教程,该教程为您构建了一本书评应用程序。除了我提交评论时,一切似乎都有效。当我这样做,我得到这个错误:Rails应用程序中的未定义方法
undefined method `book_id=' for nil:NilClass
这里是我的评论控制器:
class ReviewsController < ApplicationController
before_action :find_book
def new
@review = Review.new
end
def create
@reivew = Review.new(review_params)
@review.book_id = @book.id
@review.user_id = @current_user.id
if @review.save
redirect_to book_path(@book)
else
render "new"
end
end
private
def review_params
params.require(:review).permit(:rating, :comment)
end
def find_book
@book = Book.find(params[:book_id])
end
end
这是我的评价模型:
class Review < ApplicationRecord
belongs_to :book
belongs_to :user
end
这里是我的书型号:
class Book < ApplicationRecord
belongs_to :user
belongs_to :category
has_many :reviews
has_attached_file :book_img, styles: { book_index: "250x350>", book_show: "325x475>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :book_img, content_type: /\Aimage\/.*\z/
end
我觉得我有蜜蜂n在过去两个小时阅读帮助论坛。我卡住了。任何帮助将非常感激!
谢谢!它现在有一个问题,这条线: @ review.user_id = @ current_user.id 它说: 未定义的方法'id'为零:NilClass –
它因为'@ current_user'为零。你在哪里设置'@ current_user'变量?如果你使用的是设计,它应该是'current_user'。顺便说一句,如果我的答案帮助你,请upvote并接受我的答案(时间限制之后)。 –
谢谢先生!这工作! –