【发布时间】: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