dimanche 7 août 2016

Search polymorphic association based on child condition in Rails

I have a polymorphic associations set up between models in my app. Associations are something similar to :

class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true end

class Article < ActiveRecord::Base has_many :comments, :as => :commentable has_one :address end

class Photo < ActiveRecord::Base has_many :comments, :as => :commentable has_one :address end

class Event < ActiveRecord::Base has_many :comments, :as => :commentable has_one :address end

class Address < ActiveRecord::Base belongs_to :event belongs_to :photo belongs_to :article end

Now I need to get a list of all comments which have address city as 'Los Angles', then how can I do that? When I make a query as:

Comments.includes(:events, ,:articles, :photos).where(:city => 'Los Angles')

Then adapter makes a join of all tables in includes list with address. First join has no alias but the other two joins of alias. But the problem is that where clause only has a condition to check for address city for events only.

Is there a Rails way to do a condition check with or where any of the three included address city is 'Los Angles'? Or I have no option except to write a custom SQL?

To add to the complexity, I would need a sort order and limit/offset for the result set also.

Aucun commentaire:

Enregistrer un commentaire