Rails undefined method

Why is this undefined? Is this related to @current_user?

I am trying to create tasks for my tasks. And the created task should receive / achievements. However, I get a GET 500 error.

This is the error I get:

NoMethodError at /achievements
==============================

> undefined method `achievements' for #<User:0x00000105140dd8>

app/controllers/achievements_controller.rb, line 5
--------------------------------------------------

``` ruby
    1   class AchievementsController < ApplicationController
    2   
    3   
    4     def index
>   5       @achievements = @current_user.achievements
    6       render :json => @achievements
    7     end
    8   
    9     def new    10       @achievement = Achievement.new

This is my code in my controller

class AchievementsController < ApplicationController


  def index
    @achievements = @current_user.achievements
    render :json => @achievements
  end

  def new
    @achievement = Achievement.new
    render :json => @achievement
  end

  #create a new achievment and add it to the current user
  #check then set the acheivments pub challenge id to the current pub challenge
  def create
    @achievement = Achievement.new achievement_params
    @achievement.user = @current_user.id
    @achievement.pub_challenge = params[:id]
    if @achievement.save
      # render :json => @achievement #{ status: 'ok'}
    else
      render :json => {:errors => @achievement.errors}
    end
  end

  def show
    @achievement = Achievement.find params[:id]
    render :json => @achievement

  end

  def destroy
    @achievement = Achievement.find params[:id]
    @achievement.destroy
  end

  private
    def achievement_params
    params.require(:achievement).permit(:pub_challenges)
    end


end
+4
source share
3 answers

You are missing a relationship has_many :achievementsin your user model.

+7
source

You need to create the ActiveRecord associations that you require:

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :achievements
end

#app/models/achievement.rb
class Achievement < ActiveRecord::Base
   belongs_to :user
end

This will give you the opportunity to call a method achievementsfor any objects Userthat you have.


Error

You have an error:

undefined method `achievements' for #<User:0x00000105140dd8>

, undefined User. , , .

, , Rails, Ruby, . , , Rails, , Models:

enter image description here

, , , , "", , .

, User achievements. , , Rails, :

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :achievements #-> what you need

   def achievements
      #this will also fix the error you see, although it fundamentally incorrect
   end
end
+6

Something that helped me with this type of error was that there was no corresponding column in the database table. Adding the desired column to the database fixed the problem.

0
source

All Articles