Optimize with joins, order, distinct on current active records / sql query


Optimize with joins, order, distinct on current active records / sql query



I am using ruby on rails 4 and postgres currently, and making distinct and sorting as in the code below.



I just have a feeling is not right and not optimized because it seems to be doing all this with an array.



How could I combine this all into one activerecords query ?


ads1 = Advertisement.where(property_id: nil)
.where(target_address_city: [property.address_city, ""],
target_address_state: [property.address_state, ""],
target_address_country_id: property.address_country_id)
# return advertisement belongs to the property
ads2 = management.property.advertisements
#combine both results
combine_ads = ads1 + ads2
#remove ads duplicate
uniq_ads = combine_ads.uniq { |ads| ads.id}
# sort by created_at desc
uniq_ads = uniq_ads.sort_by { |ads| -ads[:id]}
# do pagination
final_ads = uniq_ads.paginate(:page => params[:page], :per_page => params[:page_limit])





Did you try to craft a raw SQL request ? I know many would say ActiveRecord as been created to avoid this, but sometimes a raw request offer better performance.
– Valentin Trinqué
Jul 1 at 8:50





i think i fixed it with concat(), but do advise if that is correct
– Axil
Jul 1 at 8:51





Please, update your initial post with your progress to help us understand.
– Valentin Trinqué
Jul 1 at 9:00










By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API