2012-04-13 50 views
0

请原谅铁路noob问题。我试图显示关联记录的列表,但在处理相反方向的关联时遇到问题。如何通过Rails中的聚合关联来列出和排列关联的记录?

例如,我有

Country 
    has_many :states 
    has_many :users, :through => :events 
    has_many :venues, :through => :events 
    has_many :users 
    has_many :venues 
end 

State 
    belongs_to :country 
    has_many :cities 
end 

City 
    belongs_to :state 
    has_many :events 
end 

Event 
    belongs_to :city 
    belongs_to :user 
    belongs_to :venue 
end 

Venue 
    has_many :events 
    belongs_to :country 
end 

User 
    has_many :events 
    belongs_to :country 
end 

在国内放映视图我想列出所有活动,所有场馆和所有用户。

活动是直线前进

@country = Country.find(params[:id]) 
@events = @country.states.cities.events.find(:all) 

,但我有麻烦形象化列出用户和场地一个最好的办法。

的要求是:

  • 每个单个用户/地点应一次,没有重复列出。
  • 用户/场馆应根据他们 拥有的事件数量(对于当前国家而非总数)进行排序。

这似乎是它应该是相当简单,但随着events.includes(:user).select("DISTINCT(ID)").order(user.events.length)我一直无法生成我需要查询各种排列播放后。

我想我可能会陷入这种情绪。我非常感谢社区的一些想法和想法,以确认我是否在正确的架子上。

谢谢!

编辑

后,我有点更多的思考,我觉得从那里被国家和用户,通过事件的关联,建立直接关联之间两个协会作为地址的一部分,我的问题棱。我已经更新了上面的模型描述。

因此,在我的国家展示页面上,如何确保通过活动列出与国家相关的用户,而不是通过地址列出用户?

我也得到重复的用户。我试过使用.uniq?,但在某些情况下返回错误'nil' is not an ActiveModel-compatible object that returns a valid partial path.我也尝试使用:select => "DISTINCT(ID)",目前为止似乎更适合。但是这两种方法在数据库交互方式上有什么区别呢?

回答

3

使用:through选项与:has_many得到快速访问你的深深相关记录:

Country 
    has_many :states 
    has_many :cities, through: :states # <- 
    has_many :events, through: :cities # <- 
    has_many :users, through: :events # <- 
end 

State 
    belongs_to :country 
    has_many :cities 
    has_many :events, through: :cities # <- 
    has_many :users, through: :events # <- 
end 

City 
    belongs_to :state 
    has_many :events 
    has_many :users, through: :events # <- 
end 

而且你可以简单地输入:@country.users

UPD:

要获取国家事件的所有用户尝试:

User.where(id: @country.events.uniq.pluck(:user_id)) 
+0

感谢@jdoe,我很欣赏你的建议。我上面的示例代码不完整,我已经在使用。经过一番思考,我认为我已经将我的问题归结为两个问题:(1)我的国家和用户模型之间有两种关联; (2)我不认为我完全理解uniq!并选择不同的工作。我更新了我的问题,并提供了更多细节。感谢您的帮助。 – 2012-04-13 05:51:03

+0

检查我的UPD在答案。我想这就是你想要的。 – jdoe 2012-04-13 06:50:01

+0

谢谢jdoe,这看起来很有前途。我会让你知道我如何继续。 – 2012-04-13 06:52:47