2012-10-25 104 views
1

該圖顯示了我的數據模型的一部分。我想獲取與用戶關聯的所有項目(通過組織和items_group)。我應該如何更改模型並在控制器中寫入此查詢?使用:通過=>組織我可以得到所有items_groups,但我不知道如何包括一個關係查詢相關項目。通過多個表獲取記錄

enter image description here

class User < ActiveRecord::Base   
    has_and_belongs_to_many :organizations 
    has_many :items_groups, :through => :organizations   
end 

class Organization < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    has_and_belongs_to_many :items_groups 
    has_many :items, :through => :items_groups 
end 

class ItemsGroup < ActiveRecord::Base 
    has_many :items, :inverse_of => :items_group 
    has_and_belongs_to_many :organizations 
    has_many :users, :through => :organizations    
end 

回答

4

我認爲您可能需要重新做到這一點,並找到加入您的用戶的項目。

你可以在你的用戶類中定義這樣的方法:

def items 
    Item.joins(:items_group => {:organizations => :users}).where("users.id" => self.id).select("distinct items.*") 
end 

返回將只讀明確select的,因爲,但我想你會想,要避免返回單個項目多個項目比一次。

+0

工作!非常感謝... – migu

0

如果你在你的模型設定的關係,這應該工作:

users.organizations.item_groups.items 

雖然它的工作你的模型應該包含這樣的:

class User < ActiveRecord::Base   
    has_many :organizations, :through => :organization_users 
end 

class Organization < ActiveRecord::Base 
    has_many :item_groups, :through => :items_groups_organizations 
end 

class ItemsGroup < ActiveRecord::Base 
    belongs_to :item 
end 

希望它適合你!

+0

我不相信那是有效的。我想你嘗試在'組織'上調用'item_groups'時會出錯。對你起作用嗎? – Shadwell

+0

當使用has_and_belongs_to_many(所以我不需要爲聯合表創建模型)時,我在Rails 3.2.8中得到了這個:NoMethodError異常:#未定義的方法'items_groups'。 – migu