我试图让用户拥有多个目标,然后让用户看到自己的目标。 我的欢迎控制器代码失败:
class WelcomeController < ApplicationController
def index
if user_signed_in?
@goals = current_user.goals.all
else
@goals = Hash.new
end
end
end
User.rb是这样的:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :goals
end
我的目标.rb:
class Goal < ActiveRecord::Base
belongs_to :user
end
我得到的错误是:
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
(我在创建新目标后登录时收到此错误)
我尝试将“foreign_key:user_id”添加到我的用户模型中,但后来出现以下错误:
/Users/Thomas/newyears/app/models/user.rb:7: syntax error, unexpected tSYMBEG, expecting keyword_do or '{' or '(' has_many :goals, foreign_key :user_id ^
在第3行的路线文件中,如下所示:
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
答案 0 :(得分:2)
我猜,目标表中缺少user_id列。
只需在控制台中运行该命令即可创建迁移
rails generate migration AddUserRefToGoals user:references
它将生成迁移文件。
class AddUserRefToGoals < ActiveRecord::Migration
def change
add_reference :goals, :user, index: true
end
end
然后执行rake db:migrate
希望,它会解决你的问题。