ruby-on-rails - 在当前活动记录/ sql 查询上使用连接、顺序、不同进行优化
问题描述
我目前在 rails 4 和 postgres 上使用 ruby,并按照下面的代码进行区分和排序。
我只是有一种感觉是不对的而且没有优化,因为它似乎是用一个数组来做这一切的。
我怎样才能将这一切组合成一个 activerecords 查询?
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])
解决方案
推荐阅读
- javascript - 未捕获的 TypeError:peerConnection.addstream 不是函数?
- xml - 是否有可能/如何使用 XSLT 2.0 将字符串 XML 转换为 XML?
- c# - 如何创建一个可用的 MSBuild arcive 来编译 C# 项目
- laravel - Laravel 重定向在整个项目中根本不起作用
- android - 通过模型类从 firebasedatabase 获取电话号码时出现空指针异常
- nginx - 将链接 /id 重定向到新域并排除 nginx 中的剩余部分
- c# - 将大型 Zip 文件从一个位置移动到另一个位置 - C#
- java - 如何在没有androidx的情况下制作菜单
- javascript - VisualStudio 2015 中的打字稿设置给出错误:“未定义导出”。如何正确设置?
- php - 错误尝试获取非对象的属性“id_mascota”