Reputation: 6098
I'm working with Rails, and when setting up some tests I encountered:
ActiveModel::MissingAttributeError:
can't write unknown attribute `group_id`
I'm guessing the issue is in my relations. I have
class Group < ActiveRecord::Base
has_many :transactions
has_many :users
end
And
class Transaction < ActiveRecord::Base
belongs_to :group
belongs_to :user
end
And lastly,
class User < ActiveRecord::Base
belongs_to :group
has_many :transactions
end
I saw that someone had the same error because they were using has_one
rather than belongs_to
and needed to add an ID column to their DB. I'm using belongs_to
though, so I don't think that's what I need? Any ideas?
Upvotes: 1
Views: 4915
Reputation: 76784
Looks like you don't have the group_id
column in your db.
You must remember that Rails is built on top of a relational database, which means that you can access "related" data by referencing a foreign_key
.
When setting up a belongs_to
/ has_many
association, the belongs_to
table needs to have the appropriate foreign key (in your case group_id
):
Your error doesn't state which model you're receiving the exception for; I would hazard a guess that it's User
or Transaction
.
--
To fix it, I would recommend creating a migration to add the group_id
attribute to the appropriate model:
$ rails g migration AddGroupId
#db/migrate/add_group_id____________.rb
class AddGroupID < ActiveRecord::Migration
def change
add_column :users, :group_id, :integer
end
end
$ rake db:migrate
Upvotes: 1
Reputation: 653
Unless you created the model you are referring to with a migration that had references, you will still need a migration in your database. An easy way to check if the database has one is to visit your some_project_root/db/schema.rb
. If you don't see a the field you want there then you will have to generate one. The way you would do so is to run a rails g migration AddXidToY x_id:integer
. It should set a field up for the id in the table you want.
Upvotes: 1