简体   繁体   中英

How to sort by an associated column in this active record query

I need a few queries sorted by an associated model. I have a list of Customers that I get and I need to make sure the customer list is sorted by the last Message they received. Here are the current queries:

  @open_customers = @company.customers.open.includes(:last_received_message)
  @your_customers = current_user.customers.includes(:last_message)
  @sidebar_customers = current_company.customers.open_or_claimed.
    where("user_id = ? OR user_id IS NULL", current_user.id).
    order(aasm_state: :asc).includes([:last_received_message, :user])

these are three separate queries.

@open_customers needs to be sorted by the created_at of last_received_message @your_customers needs to be sorted by the created_at of last_message @sidebar_customers needs to be sorted by the created_at of last_received_message

thanks!

You might try checking out Section 14: scopes here: http://guides.rubyonrails.org/active_record_querying.html

Also this website has a course called Rails 4 Outlaws that does a great job teaching scopes: https://www.codeschool.com

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