简体   繁体   中英

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 . Then you want to provide a condition on your join where you only select catalogs_customers with that catalog_id . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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