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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在UUID和整数字段上的多态关联前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_1@给定整数和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

猜你在找的Ruby相关文章