【问题标题】:ActiveModel::MissingAttributeError in Controller #create控制器中的 ActiveModel::MissingAttributeError #create
【发布时间】: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


【解决方案1】:

CreateUser 迁移似乎不正确。它不应该引用项目。项目应引用用户,您已正确完成。

我相信这会让 ActiveRecord 感到困惑

尝试从 UserCreate 迁移中删除 t.references :projects,然后重试

【讨论】:

  • 我尝试删除建议的代码,然后运行 ​​rake db:migrate 并重新启动服务器,只是为了确定,但没有任何改变
  • 您是否在更改迁移之前回滚了迁移?您需要删除 users 表上由 t.references :projects 创建的 project_id
  • 是的,我也尝试过 '@projects.user' = '@user',但这也让我无法写入未知属性 'user_id'
  • 请在此处发布您的 scheme.rb。
  • 看,t.integer "users_id" 不正确。如果您的模型的关系看起来像 project belongs_to: user user has_many :projects,您应该从您的 create_users 迁移中删除 t.references :projects,并将 t.integer :user_id 添加到您的 create_projects 迁移中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 2015-11-20
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多