【问题标题】:ActiveModel::UnknownAttributeError: unknown attribute when seeding belongs_to relationshipActiveModel::UnknownAttributeError:播种belongs_to关系时的未知属性
【发布时间】:2018-01-19 04:20:38
【问题描述】:

试图建立 has_many/belongs_to 关系。 一个用户有_许多脚本,一个脚本属于_一个用户。

播种脚本时,我收到此错误:

ActiveModel::UnknownAttributeError: 未知属性 'user_id' for 脚本。

我认为迁移中的这一行会为脚本创建一个 user_id 属性?

t.belongs_to :user, index: true, foreign_key: true

app/models/script.rb

class Script < ApplicationRecord
  belongs_to :user
  has_many :commits
  has_many :script_users, through: :commits, source: :user
end

app/models/user.rb

class User < ActiveRecord::Base
  has_many :scripts
  has_many :used_scripts, through: :commits, source: :script
  has_many :commits
end

db/migrate/20171231022826_create_scripts.rb

class CreateScripts < ActiveRecord::Migration[5.1]
  def change
    create_table :scripts do |t|
      t.string :name
      t.string :skill
      t.string :bot_for
      t.string :game_for

      t.belongs_to :user, index: true, foreign_key: true

      t.timestamps
    end
  end
end

db/seeds.rb

admin = User.create!(
  email: 'a@a.com',
  password: 'adminadmin',
  password_confirmation: 'adminadmin'
)

script = Script.create!(
  name: 'YWoodcutter',
  skill: 'Woodcutting',
  bot_for: 'Android',
  game_for: "CandyLand,
  user_id: admin.id
)

ActiveModel::UnknownAttributeError: 未知属性 'user_id' for 脚本。 我确保 rake:db reset 并且仍然出现错误。

谢谢

更新:

我做了一些事情,现在工作正常。我相信问题可能是我的用户迁移是在我的脚本迁移之后创建的。用户迁移应该在脚本之前完成,所以我更改了日期以更改它们迁移的顺序。rake rake db:rollback 和 db:reset 也是很好的衡量标准。

【问题讨论】:

  • 提交表中有user_id 吗?

标签: ruby-on-rails activerecord ruby-on-rails-5


【解决方案1】:

belongs_toreference 的别名,应该和references 一样工作

如果它不适合您,请尝试以下解决方案

class CreateScripts < ActiveRecord::Migration[5.1]
  def change
    create_table :scripts do |t|
      t.string :name
      t.string :skill
      t.string :bot_for
      t.string :game_for

      t.references :user, index: true, foreign_key: true

      t.timestamps
    end
  end
end

【讨论】:

  • 是的,我在研究这个时了解到 :) 我刚刚尝试了 t.references 并且仍然遇到同样的问题。
  • 你能不能在rails consoleUser.last.scripts试试这个,让我知道它返回了什么。
  • 我得到一个错误:ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column scripts.user_id does not exist
  • 奇怪!,应该可以了,能否请您回滚此迁移并重试?
  • 我做了一些事情,现在工作正常。我相信问题可能是我的用户迁移是在我的脚本迁移之后创建的。用户迁移应该在脚本之前完成,所以我更改了日期以更改他们迁移的顺序。rake rake db:rollback 和 db:reset 也是很好的措施。感谢您抽出宝贵时间提供帮助!
【解决方案2】:

使用下面的行创建模型

rails g model script references:user

默认会在迁移文件的下面一行

t.references :user, foreign_key: true

并在脚本模型中添加belongs_to :user。在 rails 5 中可能是 t.references :user 而不是 t.belongs_to :user

【讨论】:

  • 这是我原来的,谢谢。我设法以某种方式解决它,更新了 OP 的详细信息。
猜你喜欢
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多