2010-05-14 53 views
2

我一直在試圖解決這個問題幾個小時,現在還沒有能夠拿出一個乾淨的解決方案。看來我不是軌太好......如何在Ruby on Rails中以多對多的關係對對象進行排序?

反正,我有以下幾點:

Diagram

在代碼:

class Article < ActiveRecord::Base 
    has_many :line_aspects 
    has_many :aspects, :through => :line_aspects 
    #plus a 'name' field 
end 

class LineAspect < ActiveRecord::Base 
    belongs_to :article 
    belongs_to :aspect 
    #plus a 'value' field 
end 

class Aspect < ActiveRecord::Base 
    has_many :line_aspects 
    has_many :articles, :through => :line_aspects 
    #plus a 'name' field 
end 

現在,我想什麼做,就是分兩步來分類。首先按照他們的Articles.name排序,然後在Aspect.name中排序(注意,不是中間人)。

例如,按字母順序(抱歉,如果符號是不正確的):

[{ 
    article => 'Apple', 
    line_aspects => [ 
     {:value => 'red'}, #corresponding to the Attribute with :name => 'color' 
     {:value => 'small'} #corresponding to the Attribute with :name => 'shape' 
    ] 
},{ 
    article => 'Watermelon', 
    line_aspects => [ 
     {:value => 'green'}, #corresponding to the Attribute with :name => 'color' 
     {:value => 'big'} #corresponding to the Attribute with :name => 'shape' 
    ] 
}] 

再次注意,這些是由縱橫名稱排序(形狀之前的顏色),而不是每一行的具體值(紅色前綠色)。我的意圖是在視圖中的表格中顯示這些內容。

有了這樣的結果:

Table

這是我使用的代碼:我還沒有找到一個很好的辦法做到這一點的軌道,但(而不是訴諸

<table> 
    <tr> 
    <th>Category</th> 
    <% @articles.each do |article| -%> 
     <th><%= link_to article.name, article -%></th> 
    <% end -%> 
    </tr> 

    <% @aspects.each do |aspect| -%> 
    <tr> 
     <td><%= aspect.name -%></td> 

     <% aspect.line_aspects.each do |line_aspect| -%> 
     <td><%= line_aspect.value %></td> 
     <% end -%> 
    </tr> 
    <% end -%> 
</table> 

N個查詢)。任何人都可以告訴我一個很好的方法來做到這一點(即使改變了觀點,如果我的方法是錯誤的)?

(我發現了一個similar question in hyphen

更新:這是我怎麼會做它在SQL:

SELECT line_aspects.value FROM line_aspects, aspects, articles 
WHERE articles.id = line_aspects.article_id 
    AND aspects.id = line_aspects.aspect_id 
ORDER BY aspects.name, articles.name 

但我想做到這一點的軌道的方式。

更新:添加了視圖代碼。這可能會讓我的困境更好一些。

+0

我有兩個解決方案來排序許多一對多的關係。看到[類似的問題](http://stackoverflow.com/questions/10417901/rails-how-to-sort-many-to-many-relation/43781591#43781591) – 2017-05-04 11:32:18

回答

3

嘗試對方的回答後,我發現了一種從模型做到這一點。我不確定這是否是正確的方法,但它似乎是一個可行的解決方案(讓數據庫引擎對其進行排序)。

在上述方面的模型我改變了這一行:

has_many :line_aspects 

進入這個:

has_many :line_aspects, :include => :article, :order => 'articles.name' 

我還是想從更多的人,如果可能的聽,雖然。

1

這只是一個部分解決方案,因爲它不能完全解決您的問題。

您可以使用named_scope按相應的字段排序模型。沿線的東西: named_scope :ordered, :order => "name ASC"

這是一個簡單的解決方案(至少語法上,不知道複雜性)。我可以預見的唯一問題是,您無法複合多個named_scopes以在單個查詢中進行排序。

對於第二種,您可以在獲得的集合上使用Enumerable#sort_byarray.sort

希望這有助於一點:)

+0

感謝您的幫助。 – 2010-05-14 05:52:59

0

該查詢獲取所有文章和渴望負荷的方面,並通過項目名稱和ascpect名稱對其進行排序:

@articles = Article.all(:include => [ :aspects ], :order => "articles.name asc, aspects.name asc") 
相關問題