我正在尝试将STI和多态关联与以下结构相结合的一些问题:
class User < ActiveRecord::Base
end
class Runner < User
has_many :subscriptions, as: :subscriber, :dependent => :destroy
has_many :areas, through: :subscriptions
end
class Trainer < Runner
end
class Subscription < ActiveRecord::Base
belongs_to :subscriber, polymorphic: true
belongs_to :area
end
class Area
end
当我在控制台中尝试时:
Runner.find(2101).areas
SELECT "areas".* FROM "areas" INNER JOIN "subscriptions" ON "areas"."id" =
"subscriptions"."area_id" WHERE "subscriptions"."subscriber_id" = $1 AND
"subscriptions"."subscriber_type" = $2 [["subscriber_id", 2101], ["subscriber_type",
"User"]]
=> #<ActiveRecord::Associations::CollectionProxy []>
然而这位跑步者有一个记录:
#<Subscription id: 3, area_id: 2, subscriber_id: 2101, subscriber_type: "Runner", primary_area: true>
但我不明白为什么活动记录正在寻找用户而不是跑步者。
知道为什么吗?还是更好的设计?
答案 0 :(得分:8)
来自rails文档
将多态关联与单个表结合使用 继承(STI)有点棘手。为了协会 按预期工作,确保存储STI的基本模型 多态关联的类型列中的模型。接着说 使用上面的资产示例,假设有客户帖子和成员 使用帖子表进行STI的帖子。在这种情况下,必须有一个 在posts表中输入列。
像这样更改您的订阅类
class Subscription < ActiveRecord::Base
belongs_to :subscriber, polymorphic: true
belongs_to :area
def subscriber_type=(sType)
super(sType.to_s.classify.constantize.base_class.to_s)
end
end