问题
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:
ActiveModel::UnknownAttributeError: unknown attribute 'user_id' for Script.
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: '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: unknown attribute 'user_id' for Script. I've made sure to rake:db reset and still get error.
Thank you
UPDATE:
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.
回答1:
belongs_to
is an alias of reference
and it should work same as 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
回答2:
Create Model with below line
rails g model script references:user
It will by default below line in migration file
t.references :user, foreign_key: true
and add belongs_to :user
in script model . It might be t.references :user
in rails 5 not t.belongs_to :user
来源:https://stackoverflow.com/questions/48334075/activemodelunknownattributeerror-unknown-attribute-when-seeding-belongs-to-re