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

ruby-on-rails – 在UUID和整数字段上的多态关联

发布时间:2020-12-16 21:35:37 所属栏目:百科 来源:网络整理
导读:给定整数和uuid主键的表格集成多态连接(has_many)的最佳方式是什么?例如: class Interest ActiveRecord::Base # id is an integer has_many :likes,as: :likeableendclass Post ActiveRecord::Base # id is a UUID has_many :likes,as: :likeableendclass
给定整数和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

得到:

PG::UndefinedFunction: ERROR: operator does not exist: integer = character varying
LINE 1: …interests” INNER JOIN “likes” ON “interests”.”id” = “likes”….
^
HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.
: SELECT “interests”.* FROM “interests” INNER JOIN “likes” ON “interests”.”id” = “likes”.”likeable_id” WHERE “likes”.”user_id” = $1 AND “likes”.”likeable_type” = $2

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

解决方法

我对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

(编辑:李大同)

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

    推荐文章
      热点阅读