开发者

Querying a polymorphic association

I have a polymorphic association like this -

class Image < ActiveRecord::Base
  has_one :approval, :as => :approvable
end

class Page < ActiveRecord::Base
  has_one :appro开发者_JAVA技巧val, :as => :approvable
end

class Site < ActiveRecord::Base
  has_one :approval, :as => :approvable
end

class Approval < ActiveRecord::Base
  belongs_to :approvable, :polymorphic => true
end

I need to find approvals where approval.apporvable.deleted = false

I have tried something like this -

@approvals = Approval.find(:all, 
   :include => [:approvable], 
   :conditions => [":approvable.deleted = ?", false ])

This gives "Can not eagerly load the polymorphic association :approvable" error

How can the condition be given correctly so that I get a result set with approvals who's approvable item is not deleted ?

Thanks for any help in advance


This is not possible, since all "approvables" reside in different tables. Instead you will have to fetch all approvals, and then use the normal array methods.

@approvals = Approval.all.select { |approval| !approval.approvable.deleted? }


What your asking, in terms of SQL, is projecting data from different tables for different rows in the resultset. It is not possible to my knowledge.

So you'll have to be content with:

@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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜