我一直在試圖解決這個問題幾個小時,現在還沒有能夠拿出一個乾淨的解決方案。看來我不是軌太好......如何在Ruby on Rails中以多對多的關係對對象進行排序?
反正,我有以下幾點:
在代碼:
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>
<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
但我想做到這一點的軌道的方式。
更新:添加了視圖代碼。這可能會讓我的困境更好一些。
我有兩個解決方案來排序許多一對多的關係。看到[類似的問題](http://stackoverflow.com/questions/10417901/rails-how-to-sort-many-to-many-relation/43781591#43781591) – 2017-05-04 11:32:18