简体   繁体   中英

meta_search order by count

I have these models and I'm playing with meta_search to order it.

class Company < ActiveRecord::Base
  has_many :delivers
  has_many :estimates, :through => :deliver
end

class Estimate < ActiveRecord::Base
  has_many :delivers, :dependent => :destroy
  has_many :companies, :through => :delivers
end

class Deliver < ActiveRecord::Base
  belongs_to :estimate
  belongs_to :company
end

As you can see a company has many estimates and I need a filter to show companies in this order: from company who has the highest number of estimates to company that has the lowest number of estimates.
I'd like to have a sort link for it, something like:

= sort_link @search, :estimates_asc

I know that I can order in that way companies with this statement

Company.joins(:estimates).sort_by{|x| -x.estimates.size}

Thanks for helping me.

This is my case and try it in your project, I'll help you with what I can:

So I have cars table with carname_id and carmodel_id in it. then 2 more tables for carnames and carmodels both with name and id in it. now let's say I have carname Mercedes with id 2 and carmodel S classe with id 5, in this case my cartable will contain values 2 and 5 Mercedes S classe.

To sort them by fields I did this way:

in cars controller:

  @search = Car.search(params[:search])
    @search.meta_sort ||= 'created_at.desc'  <-- this line is for default order display, you can use any other field
    @cars = @search.all.paginate :page => params[:page], :per_page => 5

and in view

<%= sort_link @search, :carname_name,  "Car make" %>  <-- carname is the field from 

    car table where the carname id is stored and name is the he name itself for this id that's in carname table

<%= sort_link @search, :carmodel_name, "Car model"%>

that's all good now.

in your case I just assume it will be something like

<%= sort_link @search, :company_estimate, "Car make" %>

hope it 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