J Seabolt
J Seabolt

Reputation: 2998

undefined method in Rails app

I am fairly new to Rails, and I am following an online tutorial that has you build a book review app. Everything seems to work except for when I submit a review. When I do, I get this error:

undefined method `book_id=' for nil:NilClass

Here is my reviews controller:

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

Here is my Review model:

class Review < ApplicationRecord

belongs_to :book
belongs_to :user

end

Here is my Book model:

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

I feel like I've been reading help forums for the past two hours. I'm stuck. Any help would be very appreciated!

Upvotes: 1

Views: 140

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

There's a typo in review in your create action.

Change the following line

@reivew = Review.new(review_params)

to

@review = Review.new(review_params)

The reason for the error is that @review is nil and you can't call the method book_id on a nil object.

Upvotes: 1

Related Questions