加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 将STI和多态与rails 4相结合

发布时间:2020-12-17 03:37:56 所属栏目:百科 来源:网络整理
导读:我正在尝试将STI和多态关联与以下结构相结合的一些问题: class User ActiveRecord::Baseendclass Runner User has_many :subscriptions,as: :subscriber,:dependent = :destroy has_many :areas,through: :subscriptionsendclass Trainer Runnerendclass Su
我正在尝试将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>

但我不明白为什么活动记录正在寻找用户而不是跑步者.

知道为什么吗?还是更好的设计?

解决方法

来自rails文档

Using polymorphic associations in combination with single table
inheritance (STI) is a little tricky. In order for the associations to
work as expected,ensure that you store the base model for the STI
models in the type column of the polymorphic association. To continue
with the asset example above,suppose there are guest posts and member
posts that use the posts table for STI. In this case,there must be a
type column in the posts table.

像这样更改您的订阅类

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读