简体   繁体   中英

ORDER BY related model rails 4

I've been trying to add order_by filter in my index view on my rail project.

So far, it has worked well from some basics order by filter.

I'm now trying to order by the worker login that is attached to my project.

class Project < ActiveRecord::Base
  belongs_to :worker, class_name: User, foreign_key: "worker_id"

I use "scope" in my model to sort my data, and so far it is what i got :

  scope :worker_order, -> (order) {joins('LEFT JOIN users ON users.id = projects.worker_id')
    .order('users.login' => order)}

But i'm getting this error code :

Mysql2::Error: Unknown column 'projects.users.login' in 'order clause': SELECT projects .* FROM projects LEFT JOIN users ON users.id = projects.worker_id ORDER BY projects . users.login DESC LIMIT 30 OFFSET 0

I'v also tried other ways to do it :

  scope :worker_order, -> (order) {joins('LEFT JOIN users ON users.id = projects.worker_id')
.order(:login => order)}

Or :

  scope :worker_order, -> (order) {includes(:worker)
.order('users.login' => order)}

I don't really know if it's the good way to deal with sorting in rails, but it did well for filtering and I really don't get why my filter on Clients owning the project works when this sorting method doesn't.

Thanks for your help

Try with a String

scope :worker_order, -> (order) { joins('...').order("users.login #{order == 'desc' ? 'desc' : 'asc'}")

The order == 'desc' ? 'desc' : 'asc' order == 'desc' ? 'desc' : 'asc' part is to prevent SQL injection. If you're sure the order can't be manipulated by your users, you can write it:

scope :worker_order, -> (order) { joins('...').order("users.login #{order}")

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