2013-01-21 52 views
3

在我的Rails 3.2.11應用程序中,我有一個範圍,我正在嘗試通過基於關聯屬性進行排序。在我的情況下,我有一個用戶模型和一個配置文件模型。用戶has_one配置文件,我的作用域位於配置文件表上的屬性上。這裏的範圍:在has_one協會的Rails 3.2.11中的訂單範圍

User.rb

def self.with_default_show 
    joins(:profile).where("profiles.show_all = true") 
end 

但是我遇到的麻煩是在試圖對申報順序。例如,運行:

joins(:profile).where("profiles.show_all = true").order("profiles.first_name DESC") 

給我一個錯誤:

PG::Error: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list 

我知道我可以做.order("2")但在我的用戶表調用第二列,而不是我的配置表。如何正確地將此作用域上的順序設置爲profiles.first_name?

回答

0

什麼結束了工作是上面的兩個答案的組合:

def self.with_default_show 
    joins(:profile) 
    .where(profiles: {show_all: true}) 
    .select('users.*, profiles.first_name') 
    .order('profiles.first_name') 
end 

隨着分開我所希望的工作。

2

ORDER BY子句只能在DISTINCT應用後應用。

此外,您還必須明確地選擇您要訂購的子句。

User.select('profiles.*, profiles.first_name') 
     .joins(:profile) 
     .where("profiles.show_all = true") 
     .order("profiles.first_name DESC") 

如上所示,爲了讓您的查詢返回配置文件屬性,您還必須明確地選擇它們。

+0

謝謝。如果我將範圍更改爲「在DESC處或附近出現語法錯誤」SELECT DISTINCT配置文件。*,profiles.first_name DESC FROM'。 – tvalent2

+0

從select中刪除'desc',因爲它將按' ..看到我上面的更新後的帖子。 –