Search code examples
ruby-on-railshas-one

Need help resolving NoMethod Error


I need help resolving an error. I have been researching this for a while now and just can't seem to figure out how to fix this. Thanks in advance for any assistance. The goal is to update the field 'industry' in my reviewers table.

The error:

NoMethodError (undefined method `find' for #<Reviewer:0x007fee8dbb3f40>)

The code where this error is contained in my reviewers_controller where I set the controller:

def set_reviewer
  @reviewer = current_user.reviewer.find(params[:id])
end

Here is the update method:

  def update
    if @reviewer.update(reviewer_params)
      render json: @reviewer
    else
      render json: @reviewer.errors, status: :unprocessable_entity
    end
  end

Here are my models:

class Review < ApplicationRecord
  belongs_to :reviewer
end


class User < ApplicationRecord
  include Authentication
  has_one :reviewer
  has_many :reviews, through: :reviewer
end

class Reviewer < ApplicationRecord
  belongs_to :user
end

In set_reviewer I tried .find_by and that did not work. I have read the documentation on the has_one macro and .find(), but am just spinning my wheels. Any help is greatly appreciated. Thank you so much!


Solution

  • You can set the reviewer by doing this:

    @reviewer = current_user.reviewer
    

    current_user.reviewer will return the associated reviewer object. You're getting this error because you're trying to call find on the reviewer object itself.