2012-06-30 61 views
1

我試圖掌握如何在Rails中使用關聯,特別是何時和何時不寫顯式SQL代碼。Rails 3:使用has_many進行對象鏈接:通過關聯

在我的申請,我有四個型號,其定義如下:

class User < ActiveRecord::Base 
    has_many :comments 
    has_many :geographies 
    has_many :communities, through: :geographies 

class Comment < ActiveRecord::Base 
    belongs_to :user 

class Community < ActiveRecord::Base 
    has_many :geographies 
    has_many :users 

class Geography < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :community 

用戶可以發表評論,並關聯到通過地理表中的一個或多個社區(地理表存儲user_idcommunity_id)。

我有一個索引操作列出所有評論,我想按社區過濾。給定一個評論對象,我可以通過comment.user獲得用戶對象,但我無法鏈接超出該範圍(即,像comment.user.geography(0).community這樣的東西不起作用)。

看來這個對象鏈接是rails的一個關鍵特性,但它是否適用於has_many:通過關聯?以我的例子來說,是否有可能通過使用對象鏈接從評論對象中獲取社區對象,或者當我給出評論對象時,是否需要編寫SQL來獲取用戶以外的任何內容?

回答

0

由於用戶與多個社區相關的,你需要告訴ActiveRecord的(或原始SQL)你想要的社區:

comment.user.communities #=> should give you all the communities 

如果你不特別關心獲取所有社區,只是想得到任何社區

comment.user.communities.first #=> should give you the first community 

但是,一般來說,你會對一個特定的社區感興趣,根據一個條件。

comment.user.communities.where(name: 'Europe') #=> should give you the European community. 
0

我不認爲你需要地域表。

嘗試

class Community < ActiveRecord::Base 
    has_many :users 
end 

class User < ActiveRecord::Base 
    belongs_to :community 
    has_many :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :user 
end 

然後你就可以訪問評論的用戶的團體像 @comment.user.community

+0

謝謝,但我需要有一個用戶屬於多個社區的選項。我相信你所描述的模型將用戶限制在一個社區(如果我錯了,請糾正我)。 – ntaj

+0

糟糕,你是對的。我誤讀了。我想如果你只是把你的Community.rb中的行改爲'has_many:users,:through =>:geographies'。然後你可以說'@ comment.user.communities'這樣的東西來獲得所有的用戶共享,並從那裏指定 –

+0

感謝theButler。 Salil是對的,我需要從所有返回的社區中選擇一個社區(首先,最後等)。此外,我可以使用您描述的鏈接訪問社區,即使不包含':through:geographies'行,它似乎也可以工作。 – ntaj

相關問題