在 Rails 中为模型关联创建别名时没有这样的列

No such column when creating an alias for a model association in Rails

我想在 UserTask 模型之间创建一对多关联。在我的用户模型中,我想给它起别名 owner 并将用户的任务称为 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

当我尝试检索任务列表时,我 运行 遇到了这个错误:

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" = ?

当我的数据库中没有存储该名称的属性时,为什么它指的是 owner_type

这是您更正后的版本:

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 选项?

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 a has_many association will use person_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 a belongs_to :person association will use person_id as the default :foreign_key. Similarly, belongs_to :favorite_person, class_name: "Person" will use a foreign key of favorite_person_id.

在 Rails 中,设置 polymorphic relationships 时使用 :as 选项。在多态关系中,other 可以是几个不同的模型。这就是为什么 tasks.owner_type 列是必需的 - 它告诉 Rails 在加载 owner 关系时要查看哪个 table。

解决方案是创建一个 tasks.owner_type 列或按如下方式设置关系:

class User < ActiveRecord::Base
    has_many :owned_tasks, 
             class_name: "Task", 
             foreign_key: :owner_id
end

class Task < ActiveRecord::Base
    belongs_to :owner, class_name: "User"
end