【发布时间】:2015-08-31 21:00:44
【问题描述】:
我有一个带有
的 rails 应用程序
1)用户模型
class User < ActiveRecord::Base
has_secure_password
has_many :projects
end
2) 项目模型
class Project < ActiveRecord::Base
belongs_to :user
end
3) 在 db/migrate 中创建用户
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.references :projects
t.timestamps null: false
end
end
end
4) 在 db/migrarte 中创建项目
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :name
t.string :description
t.references :users
t.timestamps null: false
end
end
end
现在在我的控制器中,我有一个函数
def create
@project = Project.new(project_params)
@user = User.find(session[:user_id])
if @project.save
@user.projects << Project.find(@project.id)
redirect_to '/'
else
redirect_to '/project/create'
end
end
但是当我打电话给http://localhost:3000/project/new 时,我收到以下错误:-
-ProjectController#create 中的NoMethodError
-#用户的未定义方法“项目”
与
@user.projects << Project.find(@project.id)
在提取的源中突出显示。
我在 has_many 关系中输入的记录是正确的,还是我的语法错误?
我在服务器的控制台中运行了以下代码,
user = User.find(1)
user.projects
我收到此错误消息:
NoMethodError: undefined method `projects' for #<User:0x00000001f5b508>
from /home/harshil/.rvm/gems/ruby-2.2.1/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'
from /home/harshil/.rvm/gems/ruby-2.2.1/gems/activemodel-4.2.4/lib/active_model/attribute_methods.rb:433:in `method_missing'
谢谢
【问题讨论】:
-
这看起来不像是一个有效的代码:
t.refrences :users。它真的运行了还是打错了? -
感谢您指出这一点
-
那改变有帮助吗?
-
不,还是一样的错误
标签: ruby-on-rails ruby ruby-on-rails-4 model-view-controller