2012-10-25 98 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