2014-08-27 66 views
2

我有以下的关联:统一两个查询为CURRENT_USER Rails中

主机和订单User has_many HostsHost has_many Orders

我嵌套的路线,所以当用户希望看到订单,这将有要通过主机(/hosts/:id/orders

我想避免用户访问其他用户的订单,所以我有这个在我的索引行动:

def index 
    host = current_user.hosts.find(params[:host_id]) 
    redirect_to :back, alert: 'Host was not found' if host.nil? 
    orders = host.orders.includes(:order_state).order('id ASC') 
end 

正如你所看到的,我打了两次DB。一个用于查找主机是否存在current_user,另一个用于查找该主机的订单。

如何在一个查询中执行此操作?

回答

1

尝试这样:

orders = Order.joins(:host) 
       .includes(:order_state) 
       .where(hosts: { user_id: current_user.id, id: params[:host_id] }) 
       .order('orders.id ASC') 
redirect_to :back, alert: 'Orders for selected host not found' unless orders.any? 

如果你想给不发现你不能与一个查询做主机用户警报。

+0

如果'''''''redirect_to'没有使用'unless'的语法吗? – tolgap 2014-08-28 09:54:33

0

正如sufleR已经提到的,如何区分no orders for the given hosthost not found可能不是一个简单的方法。然而,代码可以更简单:

class User < ActiveRecord::Base 
    has_many :hosts 
    has_many :orders, through: :hosts # !!! 
end 

orders = current_user.orders.includes(:order_state).order(:id). 
    where(host_id: params[:host_id])