2015-07-13 13 views
13

Đưa ra các bảng có các phím chính là integeruuid 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ì ?

Trả lời

-3

Tôi không giỏi với ActiveRecord, và điều này chắc chắn không phải là câu trả lời bạn đang tìm kiếm, nhưng nếu bạn cần một * workaround xấu xí tạm thời cho đến khi bạn có thể tìm thấy một giải pháp, bạn có thể ghi đè lên các getter:

class User 
    def interests 
    self.likes.select{|like| like.likeable._type == 'Interest'}.map(&:likeable) 
    end 
end 

* Rất xấu xí vì nó sẽ tải tất cả những cầu thủ như người dùng và sau đó sắp xếp chúng

EDIT tôi thấy this interesting article:

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

Đ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'. –

Các vấn đề liên quan