简体   繁体   中英

Rails Includes with ordering not by ID

I have a simple include statement in my controller but the order for the included table is by default id. In my case I need to order the element in the same way as the uuid is received.

Query:

compare_uuids = {xyz, ytb, tyd}
@books = Book.where(uuid: compare_uuids).includes(:venue, :related_publisher, :related_author) 

The above expression is responding well but say if the uuid ordering with their id are as:

id     uuid
5      xyz
1      ytb
2      tyd

The expressions that make up when the statement run is order by id. So the uuid order is lost. Is there any work around to it.

Just try this...

has_many :books, :order => 'priority DESC'

In rails 4 this is now deprecated, the new approach would be

has_many :books, -> { order(:priority => :desc) }

Get output:

you can try

Authors.books.except(:order).order('priority DESC')
# OR
Authors.books.reorder('priority DESC')

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