繁体   English   中英

RoR:如何将两列上的订单合并到 ActiveRecord 查询中?

[英]RoR: How to merge an order on two columns into an ActiveRecord query?

我正在尝试根据几列对表进行排序,以便生成的顺序代表交错的字段。

IE,

users有first_name:string和last_name:string,account有history_first_name和history_last_name,属于User。 如果用户有一个名字,它应该在列出帐户时覆盖history_first_name(即,用户已经设置了他们的名字或者他们在一个帐户上有一个历史名字)。

我正在尝试根据名字和姓氏 ASC 返回一个有序的帐户列表,无论是历史的还是用户设置的。 结果应该是 ActiveRecord 关系而不是数组。

这个查询没有达到我想要的:

@accounts = @accounts.includes(:user).order("users.first_name ASC, historical_first_name ASC, users.last_name ASC, users.last_name ASC")

因为任何history_first_names 在first_names 之前按字母顺序排列在所有first_name 之后。 你会如何写一些东西来达到这样的顺序:

Amanda Adams <- migration_first_name: Amanda, user.first_name: nil 
Bentley James <- migration_first_name: nil, user.first_name: Bentley
Cynthia Cann <- migration_first_name: Cynthia, user.first_name: nil

您想主要按 first_name 排序,如果为 null,则按 history_first_name 排序。 然后按 last_name 或history_last_name(如果为空)的顺序之后。

您可以使用COALESCE()函数(或IFNULL() )来表示它。

@accounts = @accounts.includes(:user).order(
  "COALESCE(users.first_name, users.historical_first_name) ASC",
  "COALESCE(users.last_name, users.historical_last_name) ASC"
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM