我有以下事件记录模型:
class Catalog < ActiveRecord::Base
has_and_belongs_to_many :customers
end
class Customer < ActiveRecord::Base
has_and_belongs_to_many :catalogs
end
现在在我的索引中,我想列出所有按如下方式排序的客户: 首先是已经是目录成员的成员,然后是所有其他成员。
我尝试过这样的事情:
@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')
这接近我的目标,但我得到了目录成员的所有客户(无论是什么),然后是所有其他客户。
最佳答案
你的问题有点不清楚,但我无法发表评论来询问更多,所以无论如何我都会尽力而为。
听起来您想要列出所有客户,并优先考虑与一个特定目录相关的客户,但您的代码示例并没有告诉我们您计划如何设置。我假设您有一个实例变量@catalog_id
。然后,您需要在加入时提供一个条件,仅选择具有该 catalog_id
的 catalogs_customers
。所以尝试这样的事情:
@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')
希望有帮助。
关于mysql - rails : order query by has and belongs to many presence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749368/