Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

sql - Rails Active query order by multiple values in specific order?

I have a table

Roles(id int,,name vachar(50),role enum(CAD,CA,CM,CV ))

I want select data that order by specific values in specific order . My active model query: role.order('role asc') then the result:

1 name1 CAD
2 name2 CA
3 name2 CM

But I want the result like:

1 name1 CAD
2 name2 CM
3 name2 CA

Can anyone help me? Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A portable solution would be to use a CASE statement as an inlined map in your ORDER BY:

query.order(%q(
  case role
  when 'CAD' then 1
  when 'CM'  then 2
  when 'CA'  then 3
  end
))

Keep in mind that you can ORDER BY any expression you want and a CASE certainly is an expression in SQL.

Newer versions of Rails will want you to use Arel.sql rather than a raw string:

query.order(
  Arel.sql(
    %q(
      case role
      when 'CAD' then 1
      when 'CM'  then 2
      when 'CA'  then 3
      end
    )
  )
)

And if the list is dynamic, you can build a CASE expression:

array = %w[CAD CM CA]
q     = connection.method(:quote) # Or ApplicationRecord.connection.method(:quote)
cases = array.each_with_index.map { |e, i| "when #{q[e]} then #{i}" }
query.order(Arel.sql("case role #{cases.join(' ')} end"))

All the string manipulation is a bit ugly but it is perfectly safe and you'd usually hide it in a scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...