Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join across polymorphic tables in one query?

I have 2 polymorphic associations through which I need to query.

I have a news_article table which has a polymorphic association to teams, players, etc. Those teams, players, etc have a polymorphic association to photos through phototenic.

I need to find all articles that have at least one picture that is 500px wide.

The Article model I have a has_many :teams (through the polymorphic table) and in the teams I have a has_many :photos (though another polymorphic table)

I thought that I could use joins like this

Article.find(:last, :joins => {:teams => :photos}, :conditions => "photos.aspect_ratio < 1.55 AND photos.aspect_ratio > 1.30")

but it is not working. Any ideas?

like image 571
tesserakt Avatar asked Oct 13 '22 23:10

tesserakt


2 Answers

Hope this is your setup...

class Article < ActiveRecord::Base
  has_many :teams
end

class Team < ActiveRecord::Base
  has_many :photos
end

class Photo < ActiveRecord::Base
  belongs_to :teams
end

Can you please use the following query and let us know if it works for you?

Article.find(:last, :include => {:teams => :photos}, :conditions => "photos.aspect_ratio < 1.55 AND photos.aspect_ratio > 1.30")

Hope It helps...

rgds, Sourcebits Team

like image 98
Sourcebits Avatar answered Nov 01 '22 11:11

Sourcebits


If you are using Rails 3 already:

Article.joins(:teams).where(condition).joins(:photos).where(condition)

If you are using Rails 2.3.8:

Article.find(:all, :include => {:teams => :photos}, :conditions => [YOUR CONDITIONS])

Hope It helps...

like image 27
KannanR Avatar answered Nov 01 '22 10:11

KannanR