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

ruby-on-rails – rails多态,包含基于类的类型

发布时间:2020-12-16 22:31:18 所属栏目:百科 来源:网络整理
导读:假设我们有这些模型 class Message belongs_to :messageable,polymorphic: trueendclass Ticket has_many :messages,as: :messageable has_many :commentsendclass User has_many :messages,as: :messageable has_many :ratingsendclass Rating belongs_to :
假设我们有这些模型
class Message
  belongs_to :messageable,polymorphic: true
end

class Ticket
  has_many :messages,as: :messageable
  has_many :comments
end

class User
  has_many :messages,as: :messageable
  has_many :ratings
end

class Rating
  belongs_to :user
end

class Comment
  belongs_to :ticket
end

现在我想加载所有的邮件(有相关的门票或用户)和热门的负载取决于类的类型,对用户的票和评价的评论

当然Message.includes(:messageable).order(“created_at desc”)将只包括直接关联的对象,但问题是如何包括从每个模型类型派生的不同的关联类型(即在这个例子中,如何以热门的方式加载用户的票证和评分)?

这只是一个简单的例子,但是甚至更复杂的情况呢,我想为用户添加其他内容,另一个关联,以及如果该关联需要更多的内容呢?

解决方法

我可以想到的唯一方式是使用通用名称复制每个模型上的关联:
class Ticket
  has_many :messages,as: :messageable
  has_many :comments
  has_many :messageable_includes,class_name: "Comment"
end

class User
  has_many :messages,as: :messageable
  has_many :ratings
  has_many :messageable_includes,class_name: "Rating"
end

Message.includes(:messageable => :messageable_includes) ...

我不知道我会用这个策略作为一个广泛的解决方案,但如果这是一个复杂的,你的情况下,它可能适用于你.

(编辑:李大同)

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

    推荐文章
      热点阅读