Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 在UUID和整数字段上的多态关联大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
给定整数和uuid主键的表格集成多态连接(has_many)的最佳方式是什么?例如:
class Interest < ActiveRecord::Base
  # id is an Integer
  has_many :likes,as: :likeable
end

class Post < ActiveRecord::Base
  # id is a UUID
  has_many :likes,as: :likeable
end

class User < ActiveRecord::Base
  has_many :likes
  has_many :posts,through: :likes,source: :likeable,source_type: "Post"
  has_many :interests,source_type: "Interest"
end

class Like < ActiveRecord::Base
  # likeable_id and likeable_type are Strings
  belongs_to :likeable,polymorphic: true
  belongs_to :user
end

许多查询工作:

interest.likes
post.likes
user.likes

然而:

user.interests

得到:

什么是最好的方式来确保正确的铸造发生?

解决方法

我对ActiveRecord不是很好,这绝对不是你要找的答案,但如果你需要一个临时的*丑恶的解决方法,直到找到一个解决方案,你可以覆盖getter:
class User
  def interests
    self.likes.SELEct{|like| like.likeable._type == 'Interest'}.map(&:likeablE)
  end
end

*非常丑,因为它将加载所有用户喜欢,然后排序

编辑我发现this interesting article

self.likes.inject([]) do |result,like|
  result << like.likeable if like.likeable._type = 'Interest'
  result
end

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 在UUID和整数字段上的多态关联全部内容,希望文章能够帮你解决ruby-on-rails – 在UUID和整数字段上的多态关联所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。