rails使查询更好

时间:2014-01-26 05:47:22

标签: mysql ruby-on-rails performance activerecord

在我的表架构中 我有“监听器”表连接到“设备”表(一对多) 现在我需要在listener表上搜索但是使用devices.id字段

我的问题是2表应该有很多记录(超过1,000,000),我担心我的查询会使应用程序崩溃 我的问题是在选择中 我想知道如何才能使这个查询更好

我对gist https://gist.github.com/anonymous/8623345

的完整查询
limit = 10
@listeners = Listener.all
@total_count = @listeners.count
@sEcho = params[:sEcho]

**@listeners =@listeners.where(" (listeners.name like ?) or (listeners.email like ?) or (countries.name like ?) or   (listeners.city like ?)  or   (listeners.id in (select listener_id from devices where id = ?))", "%#{params[:sSearch]}%", "%#{params[:sSearch]}%" , "%#{params[:sSearch]}%","%#{params[:sSearch]}%","#{params[:sSearch]}") if params[:sSearch].present?**

order_by ="listeners.id asc"
@listeners = @listeners.includes(:devices)
@listeners = @listeners.includes(:country) 
@count = @listeners.count
@listeners = @listeners.order(order_by)
@listeners = @listeners.limit(limit).offset(params[:iDisplayStart])

1 个答案:

答案 0 :(得分:0)

你需要使用kaminari或者将分页用于分页,你要使它更复杂,这是我认为最短的形式:

Listener.includes(:devices, country).where(" (listeners.name like ?) or (listeners.email like ?) or (countries.name like ?) or   (listeners.city like ?)  or   (listeners.id in (select listener_id from devices where id = ?))", "%#{params[:sSearch]}%", "%#{params[:sSearch]}%" , "%#{params[:sSearch]}%","%#{params[:sSearch]}%","#{params[:sSearch]}").limit(limit).offset(params[:iDisplayStart]||1).order(:id)