Undefined method in professors controller

Question!

I have a system that lets users or guests write a review. If users write a review it is associated with their user_id. If guests write a review they are asked to provide a username which is stored in a column called "guest" in the reviews database.

I'm not entirely sure how to do this but what I've done with the professor_controller is:

def show
    @review = Review.where(professor_id: @professor.id).order("created_at DESC")
    @avg_review = @review.average(:hw)
    if @review.user_id = !nil
        @user = User.where(id: @review.user_id) 
    else
        @user = @review.guest
    end
    render
end

However, this yields an error:

NoMethodError in ProfessorsController#show
undefined method `user_id=' for #<Review::ActiveRecord_Relation:0x007fed19228e28>

I was getting this error even before I put the if statement in. I had the same problem when my controller looked like:

def show
    @review = Review.where(professor_id: @professor.id).order("created_at DESC")
    @avg_review = @review.average(:hw)
    @user = User.where(id: @review.user_id) 
end

@review works fine so does @avg_review. The Reviews table has a user_id column and the Users table has an id column.

By : tfantina


Answers

You are getting an ActiveRecord::Relation (a collection of Reviews), not a single instance of Review. You will need to do Review.where(professor_id: @professor.id).order("created_at DESC").first or Review.find_by_user_id(@professor.id) to return a single instance.

That said, it sounds like this relationship isn't modeled properly, or there's a better way to express what you want to do through other means. Can you route take in the id of a review as a param?



Your @review variable actually holds an ActiveRecord::Relation object, like it clearly says in the error message:

NoMethodError in ProfessorsController#show
undefined method `user_id=' for #<Review::ActiveRecord_Relation:0x007fed19228e28>

That's because where always returns a Relation, even if it finds only one record.



This video can help you solving your question :)
By: admin