-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
線是造成問題。看起來它不認可這種方法,這很奇怪。
感謝您的幫助:)
你有'projects'表'user_id'列? – Pavan
粘貼您的schema.rb文件。 –
發現問題!在我過分熱情的時候,我忘了把一個外鍵添加到'projects'表中。我會加上我的更正作爲答案。 – bitfizzy