Reputation: 3311
I am trying to figure out if this activerecord query is good or should there be a better optimization for this ?
I need to combine 3 queries and make sure the results is unique. I am using .uniq
ads1 = Advertisement.where(city: property.city, state: property.state, country_id: property.address_country_id)
ads2 = Advertisement.where(city: nil, state: property.state, country_id: property.address_country_id)
ads3 = Advertisement.where(city: nil, state: nil, country_id: property.address_country_id)
combine_ads = ads1 + ads2 + ads3
uniq_ads = combine_ads.uniq { |ads| ads.id}
uniq_ads = uniq_ads.sort_by { |ads| ads.created_at}
final_ads = uniq_ads.paginate(:page => params[:page], :per_page => params[:page_limit])
status 200
present final_ads, with: Api::Presenters::AdvertisementDetail
I am using ruby on rails 4
gem 'rails', '4.2.4'
Can you review the above activerecords combined unique join and maybe provide feedback if its good or there is a better optimization way to do this ?
Upvotes: 1
Views: 51
Reputation: 13014
You should change combine_ads
to:
combine_ads = Advertisement.where(city: [property.city, nil],
state: [property.state, nil],
country_id: property.address_country_id)
.order('created_at asc')
Only extra case in above is, it will also have those rows, where city
is property.city
, but state
is nil
, which your breakdown doesn't track.
You wouldn't need to uniq_ads
either, we are already ordering with created_at
.
Upvotes: 1