2015-09-14 32 views
-1

我在我的Rails應用程序中使用Devise。 A Project屬於(設計)User。 (相關模型如下。)使用`current_user`時控制器中的設計:NameError(未定義的局部變量或方法`user_id =')

create動作稱爲ProjectsController,但是,顯示在服務器日誌中出現以下錯誤:

NameError (undefined local variable or method `user_id=' for #<Project:0x007f4c1a0aa3a8>): 
    app/controllers/projects_controller.rb:20:in `create' 

任何想法?

Project.rb

class Project < ActiveRecord::Base 
    belongs_to :user 
    has_many :timestamps 
end 

User.rb

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_many :projects 
end 

projects_controller.rb(相關部分)

class ProjectsController < ApplicationController 
    before_action :authenticate_user! 

def create 
    @project = current_user.projects.new(project_params) 

    respond_to do |format| 
     if @project.save 
     format.html { redirect_to @project, notice: 'Project was successfully created.' } 
     format.json { render :show, status: :created, location: @project } 
     else 
     format.html { render :new } 
     format.json { render json: @project.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

的routes.rb

Rails.application.routes.draw do 

    root 'static_pages#home' 

    devise_for :users 

    resources :projects do 
    resources :timestamps 
    end 

end 

這是@project = current_user線是造成問題。看起來它不認可這種方法,這很奇怪。

感謝您的幫助:)

+2

你有'projects'表'user_id'列? – Pavan

+0

粘貼您的schema.rb文件。 –

+0

發現問題!在我過分熱情的時候,我忘了把一個外鍵添加到'projects'表中。我會加上我的更正作爲答案。 – bitfizzy

回答

0

萬一別人犯同樣的錯誤,不會想到去檢查他們的數據庫模式,這裏是什麼原因導致的問題。

我忘了在projects表中添加一個外鍵(user_id),即使我在模型中添加了belongs_to關聯。

要解決這個問題,我跑以下遷移:

class AddUserToProjects < ActiveRecord::Migration 
    def change 
    add_reference(:projects, :user, foreign_key: true, index: true) 
    end 
end 

然後當然跑rake db:migrate

相關問題