2016-11-27 159 views
0
User.where(id: users_ids) 
    .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1') 
    .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1') 
    .select('users.*, names.first_name AS f_name , emails.email AS primary_email') 

我需要訂購記錄f_name。當f_namenil時,記錄將移至最後並通過電子郵件進行排序。Ruby on Rails:空值的訂單記錄

下面是查詢,

User.where(id: users_ids) 
    .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1') 
    .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1') 
    .select('users.*, names.first_name AS f_name , emails.email AS primary_email') 
    .where('names.first_name IS NOT NULL') 
    .order('f_name asc').union(
User.where(id: users_ids) 
    .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1') 
    .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1') 
    .select('users.*, names.first_name AS f_name , emails.email AS primary_email') 
    .where('names.first_name IS NULL') 
    .order('primary_email asc')) 

上面的查詢不起作用。

數據庫 - MySQL的

+0

它是如何不工作? –

+0

對不起,我忘了添加我正在使用分頁'.paginate(page:params [:page])。per_page(10)'並且錯誤'undefined method'paginate'for#' –

+0

不知道Arel :: Nodes :: Union或paginate方法來自何處。可能不是'.union',請嘗試使用'||'或'.or'(如果您使用的是Rails 5) –

回答

0

我解決不良方式這個問題,但解決

users_with_names = User.where(id: users_ids) 
         .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1') 
         .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1') 
         .select('users.*, names.first_name AS f_name , emails.email AS user_email') 
         .where('names.first_name IS NOT NULL') 
         .order('f_name asc') 

users_without_names = User.where(id: users_ids) 
          .joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1') 
          .joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1') 
          .select('users.*, names.first_name AS f_name , emails.email AS user_email') 
          .where('names.first_name IS NULL') 
          .order('user_email asc') 

@contacts = [users_with_names, users_without_names].flatten.paginate(page: params[:page], per_page: 10) 
0

這個問題是這樣解決的

joins('LEFT JOIN names ON names.user_id = users.id AND names.primary = 1') 
.joins('LEFT JOIN emails ON emails.user_id = users.id AND emails.primary = 1') 
.select('users.*, names.first_name AS f_name , emails.email AS user_email, 
      names.last_name AS l_name, names.middle_name AS m_name, ISNULL(names.first_name) AS name_present') 
.order('name_present, f_name ASC, emails.email ASC') 
.group('users.id')