1

我试图掌握如何在 Rails 中使用关联,特别是何时以及何时不编写显式 SQL 代码。

在我的应用程序中,我有四个模型,定义如下:

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 :through 关联?给定我的示例,是否可以通过使用对象链接从评论对象中获取社区对象,或者在给定评论对象时,我是否需要编写 SQL 来获取用户以外的任何内容?

4

2 回答 2

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

于 2012-07-01T05:42:15.997 回答
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.
于 2012-07-01T16:16:20.803 回答