NameError uninitialized constant Model::Object

user1558835 picture user1558835 · Dec 18, 2016 · Viewed 13.8k times · Source

I'm new to ruby on rails. Ihe error I have is

NameError in ReviewsController#create
uninitialized constant User::Review
Extracted source:
    @review = current_user.reviews.build(review_params)

I read on other stack overflow questions that usually the error for wrong names or forgetting belongs_to or has_many but I believe I've set the relations correctly. I am using the gem devise to handle the user and sign in/sign up etc

Reviews.rb

class Reviews < ActiveRecord::Base

  belongs_to :user
    belongs_to :renters

end

User.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :reviews
end

Reviews_Controller.rb

class ReviewsController < ApplicationController
  before_action :set_renter
  before_action :authenticate_user!

  def new
    @review = Reviews.new(renters: @renter)
  end

  def create
    @review = current_user.reviews.build(review_params)
    @review.renter = @renter
    @review.save 
    redirect_to @renter 
  end

  private
    def set_renter
      @renter = Renters.find(params[:renter_id])
    end

    def review_params
      params.require(:reviews).permit(:comment, :rating)
    end
end

The Renters model is working fine and similar code I have to make a new Renter is working so I am not sure what is wrong.

Answer

spickermann picture spickermann · Dec 18, 2016

ActiveRecord::Base classes are usually named in singular.

That means your class should be named Review and it should be stored in a file named models/review.rb (but still store its entries in a reviews database table).

If you do not want to follow this convention than you have to explicitly tell Rails that the class is named differently in the definition of the belongs_to and has_many association.