I am trying to make it so a user has_many goals, and then only let a user see their own goals. My welcome controller where the code is failing:
class WelcomeController < ApplicationController
def index
if user_signed_in?
@goals = current_user.goals.all
else
@goals = Hash.new
end
end
end
User.rb is like so:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :goals
end
And my Goal.rb:
class Goal < ActiveRecord::Base
belongs_to :user
end
The error I am getting is:
PG::Error: ERROR: column goals.user_id does not exist LINE 1: SELECT "goals".* FROM "goals" WHERE "goals"."user_id" = $1 ^ : SELECT "goals".* FROM "goals" WHERE "goals"."user_id" = $1
(I get this error while logged in, after having created a new goal)
I tried adding "foreign_key :user_id" to my User model but then I get the following error:
/Users/Thomas/newyears/app/models/user.rb:7: syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '(' has_many :goals, foreign_key :user_id ^
In my routes file on line 3, which looks like this:
Goalsy::Application.routes.draw do
get "mycalendar/index"
devise_for :users
devise_for :goals
resources :goals
get "welcome/index"
resources :posts
root 'welcome#index'
end
I guess, the user_id column is missing in the goals table.
Just run the command in your console to create the migration
rails generate migration AddUserRefToGoals user:references
It will generate the migration file.
class AddUserRefToGoals < ActiveRecord::Migration
def change
add_reference :goals, :user, index: true
end
end
Then do the rake db:migrate
Hope, it will fix your problem.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments