[英]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.