2012-06-30 59 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

相关问题