Interrogazione di un'associazione polimorfica
-
28-09-2020 - |
Domanda
Ho un'associazione polimorfica come questa -
class Image < ActiveRecord::Base
has_one :approval, :as => :approvable
end
class Page < ActiveRecord::Base
has_one :approval, :as => :approvable
end
class Site < ActiveRecord::Base
has_one :approval, :as => :approvable
end
class Approval < ActiveRecord::Base
belongs_to :approvable, :polymorphic => true
end
.
Ho bisogno di trovare approvazioni in cui approval.apporvable.deleted = false
Ho provato qualcosa del genere -
@approvals = Approval.find(:all,
:include => [:approvable],
:conditions => [":approvable.deleted = ?", false ])
.
Questo dà "non può caricare avidamente l'errore polymorphic Association: approvibile"
In che modo la condizione può essere data correttamente in modo da ottenere un risultato impostato con le approvazioni che è approvato l'elemento approvato non viene eliminato?
Grazie per qualsiasi aiuto in anticipo
Soluzione
Non è possibile, dal momento che tutte le "approvabili" risiedono in diverse tabelle.Invece dovrai recuperare tutte le approvazioni, quindi utilizzare i normali metodi di array.
@approvals = Approval.all.select { |approval| !approval.approvable.deleted? }
. Altri suggerimenti
Qual è la tua richiesta, in termini di SQL, sta proiettando i dati da diverse tabelle per diverse righe nel Resultset.Non è possibile a mia conoscenza.
Quindi dovrai contentare:
@approvals = Approval.all.reject{|a| a.approvable.deleted? }
# I assume you have a deleted? method in all the approvables
. I would recommend either of the answers already presented here (they are the same thing) but I would also recommend putting that deleted flag into the Approval model if you really care to do it all in a single query.
With a polymorphic relationship rails can use eager fetching on the polys, but you can't join to them because yet again, the relationships are not known so the query is actually multiple queried intersected.
So in the end if you REALLY need to, drop into sql and intersect all the possible joins you can do to all the types of approvables in a single query, but you will have to do lots of joining manually. (manually meaning not using rails' built-in mechanisms...)
thanks for your answers I was pretty sure that this couldn't be done. I wanted some more confirmation besides that I was hoping for some other soln than looping thru the result set to avoid performance related issues later Although for the time being both reject/select are fine but in the long run I will have to do those sql joins manually. Thanks again for your help!!
M