I want to create a one to many association between a User
and Task
model. In my user model I'd like to give it the alias of owner
and refer to the user's tasks as owned_tasks
.
class User < ActiveRecord::Base
has_many :owned_tasks, class_name: "Task", as: :owner
end
class Task < ActiveRecord::Base
#owner_id
belongs_to :owner, class_name: "User"
end
When I try and retrieve the list of tasks as so I run into this error:
user = User.first
user.owned_tasks
SQLite3::SQLException: no such column: tasks.owner_type: SELECT "tasks".* FROM "tasks" WHERE "tasks"."owner_id" = ? AND "tasks"."owner_type" = ?
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: tasks.owner_type: SELECT "tasks".* FROM "tasks" WHERE "tasks"."owner_id" = ? AND "tasks"."owner_type" = ?
Why is it referring to owner_type
when there's no attribute of that name stored in my database?
Here is your corrected version :
class User < ActiveRecord::Base
has_many :owned_tasks, class_name: "Task", foreign_key: :owner_id
end
class Task < ActiveRecord::Base
#owner_id
belongs_to :owner, class_name: "User"
end
:foreign_key
option ?Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and
_id
suffixed. So a Person class that makes ahas_many
association will useperson_id
as the default:foreign_key
.Specify the foreign key used for the association. By default this is guessed to be the name of the association with an
_id
suffix. So a class that defines abelongs_to :person
association will useperson_id
as the default:foreign_key
. Similarly,belongs_to :favorite_person, class_name: "Person"
will use a foreign key offavorite_person_id
.