【问题标题】:Devise: NameError (undefined local variable or method `user_id=') in controller when using `current_user`设计:使用`current_user`时控制器中的NameError(未定义的局部变量或方法`user_id =')
【发布时间】:2015-09-14 11:29:45
【问题描述】:

我在我的 Rails 应用程序中使用 Devise。 Project 属于(设计)User。 (相关型号如下。)

但是,当在ProjectsController 中调用create 操作时,服务器日志中会显示以下错误:

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

用户.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 列吗?
  • 粘贴您的 schema.rb 文件。
  • 发现问题了!在我过度热情的情况下,我忘记在projects 表中添加外键。我将添加我的更正作为答案。

标签: ruby-on-rails ruby-on-rails-4 devise has-many belongs-to


【解决方案1】:

以防万一其他人犯了同样的错误并且不想检查他们的数据库架构,这就是导致问题的原因。

我忘记将外键 (user_id) 添加到 projects 表中,即使我在模型中添加了 belongs_to 关联。

为了解决这个问题,我运行了以下迁移:

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

然后当然是跑rake db:migrate

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多