代码之家  ›  专栏  ›  技术社区  ›  Axil

Ruby on Rails 4 ActudieCordR-结合和独特的连接查询优化

  •  1
  • Axil  · 技术社区  · 6 年前

    我想弄清楚这个ActuvReCordD查询是好的还是应该有更好的优化呢?

    我需要合并3个查询并确保结果是唯一的。我正在使用.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
    

    我正在使用RubyonRails4

    gem 'rails', '4.2.4'
    

    你能回顾一下以上结合了惟一连接的activerecords吗?如果它是好的,或者有更好的优化方法可以这样做,你可以提供反馈吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   kiddorails    6 年前

    你应该改变 combine_ads 致:

    combine_ads = Advertisement.where(city: [property.city, nil], 
                                      state: [property.state, nil], 
                                      country_id: property.address_country_id)
                               .order('created_at asc')
    

    上面的唯一额外情况是,它也有那些行,其中 city property.city ,但是 state nil ,这是你的故障没有记录的。

    你不需要 uniq_ads 或者,我们已经订购了 created_at .