2012-01-03 53 views
0
class Item < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :category 
end 

class Category < ActiveRecord::Base 
    belongs_to :account 
    has_many :items 
end 

我想做到以下幾點:Rails 3.1 - 通過belongs_to關聯範圍爲多個對象?

@items = @account.items.where(...) 
@categories = @items.categories.order(...) 

@items.categories應通過belongs_to協會得到的@items所有類別。最好的我想出來的是:

@categories = @items.map{|item| item.category } 

但是沒有一個範圍來管理呢?

回答

0

既然你通過的項目會想從賬戶類別,我想你可以在你的Account模型做這樣的事情

has_many :categories, :through => :items

,然後就打電話account.categories

而且,備案,map你在那裏做n + 1的查詢(它應該是這樣的@categories = @items.includes(:category).map{...}

+0

感謝您的回答!您的suggesti on會工作,但我想在我的控制器(過濾器,搜索)中動態地更改@items,並希望將它們顯示在關聯的類別中。對不起,我沒有在我的問題中說清楚這一點。但你絕對正確的地圖命令,我應該使用包括。 – chirimoya 2012-01-03 13:29:51

相關問題