问题描述
尝试建立has_many/belongs_to关系.一个用户有多个脚本,一个脚本属于一个用户.
Trying to seed a has_many/belongs_to relationship.A user has_many scripts, a script belongs_to a user.
在播种脚本时,出现此错误:
When seeding the script, I get this error:
我认为迁移中的这一行会为脚本创建一个user_id属性吗?
I'd think that this line in my migration would create a user_id attribute for script?
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: '[email protected]',
password: 'adminadmin',
password_confirmation: 'adminadmin'
)
script = Script.create!(
name: 'YWoodcutter',
skill: 'Woodcutting',
bot_for: 'Android',
game_for: "CandyLand,
user_id: admin.id
)
谢谢
更新:
我做了几件事,现在一切正常.我认为问题可能在于我的用户迁移是在脚本迁移之后创建的.用户迁移应该在脚本之前完成,因此我更改了日期以更改迁移顺序. db:reset也很有效.
I did a few things and it's working OK now. I believe the issue may have been that my user migration was created after my script migration. The user migration should done before scripts, so I changed the dates to change the order they were migrated in. Did a rake rake db:rollback & db:reset for good measure too.
推荐答案
belongs_to
是reference
的别名,应与references
如果它不适合您,请尝试以下解决方案
If its not working for you just try with following solution
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
这篇关于ActiveModel :: UnknownAttributeError:播种belongs_to关系时为未知属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!