2016-09-15 67 views
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在過去兩個小時閱讀幫助論壇。我卡住了。任何幫助將非常感激!

回答

1

您的create操作中存在review的拼寫錯誤。

更改以下行

@reivew = Review.new(review_params) 

@review = Review.new(review_params) 

的原因錯誤是@reviewnil,你不能調用該方法book_id一個nil對象。

+0

謝謝!它現在有一個問題,這條線: @ review.user_id = @ current_user.id 它說: 未定義的方法'id'爲零:NilClass –

+1

它因爲'@ current_user'爲零。你在哪裏設置'@ current_user'變量?如果你使用的是設計,它應該是'current_user'。順便說一句,如果我的答案幫助你,請upvote並接受我的答案(時間限制之後)。 –

+0

謝謝先生!這工作! –

相關問題