2015-07-13 17 views
13

Dato tabelle con integer e uuid chiavi primarie qual è il modo migliore per integrare un join polimorfico (has_many)? Per esempio:Associazione polimorfica su campi UUID e intero

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 

Molte query funzionano:

interest.likes 
post.likes 
user.likes 

Tuttavia:

user.interests 

Dà:

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

Qual è il modo migliore per includere garantire il casting corretta accade ?

risposta

-3

Io non sono bravo con ActiveRecord, e questo non è sicuramente la risposta che state cercando, ma se avete bisogno di un * brutta soluzione temporanea finché è possibile trovare una soluzione, si poteva ignorare il getter:

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

* Molto brutto perche 'caricherà tutti i simili degli utenti e poi ordinarli

EDIT ho trovato this interesting article:

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

Restituisce un array dell'oggetto sbagliato ('Like' invece di' Interest') e il fixing per usare una mappa avrebbe un problema 'N + 1'. –

Problemi correlati