Đưa ra các bảng có các phím chính là integer
và uuid
cách tốt nhất để tích hợp một phép nối đa hình (has_many
) là gì? Ví dụ:Hiệp hội đa hình trên các trường UUID và số nguyên
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, through: :likes, source: :likeable, source_type: "Interest"
end
class Like < ActiveRecord::Base
# likeable_id and likeable_type are strings
belongs_to :likeable, polymorphic: true
belongs_to :user
end
Nhiều truy vấn làm việc:
interest.likes
post.likes
user.likes
Tuy nhiên:
user.interests
Cung cấp:
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
cách tốt nhất để bao gồm đảm bảo đúc hợp xảy ra là gì ?
Điều này trả về một mảng của đối tượng sai ('Like' thay vì' Interest') và việc sửa lỗi để sử dụng bản đồ sẽ có vấn đề 'N + 1'. –