简体   繁体   English

Rails:由has进行的订单查询并属于多个状态

[英]Rails: order query by has and belongs to many presence

I have the following active record models: 我有以下活动记录模型:

class Catalog < ActiveRecord::Base
   has_and_belongs_to_many :customers
end

class Customer < ActiveRecord::Base
   has_and_belongs_to_many :catalogs
end

Now in my index, i want to list all customers sorted like this: first the ones who already are member of the catalog, then all the others. 现在,在索引中,我要列出按这种方式排序的所有客户:首先是那些已经属于目录的客户,然后是所有其他客户。

I have tried something like this: 我已经尝试过这样的事情:

@customers = Customer.all.joins('LEFT JOIN catalogs_customers ON catalogs_customers.customer_id = customers.id').order('catalogs_customers.catalog_id DESC, customers.company_name ASC')

That is near to my goal but i got all the customers who are member of a catalog (whatever it is) and then all the other customers. 这接近我的目标,但是我得到了所有属于目录成员的客户(无论它是什么),然后是所有其他客户。

Your question is a tiny bit unclear, but I can't comment to ask more, so I'll do my best regardless. 您的问题有点不清楚,但是我无法提出更多问题,因此无论如何我都会尽力而为。 It sounds like you want to list all customers with priority given to those associated with one specific catalog , but your code samples don't tell us how you plan on setting that. 听起来您想列出所有优先于与一个特定目录相关联的客户的客户,但是您的代码示例并未告诉我们您打算如何设置。 I'll assume that you have an instance variable @catalog_id . 我假设您有一个实例变量@catalog_id Then you want to provide a condition on your join where you only select catalogs_customers with that catalog_id . 然后,您想为联接提供一个条件,即您只能选择具有该catalog_id catalogs_customers So try something like: 因此,尝试类似:

@customers = Customer.all.joins('LEFT JOIN catalogs_customers ON catalogs_customers.customer_id = customers.id').
.where(catalogs_customers: { catalog_id: @catalog_id }).
order('catalogs_customers.catalog_id DESC, customers.company_name ASC')

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM