我试图掌握如何在 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_id
和community_id
)。
我有一个列出所有评论的索引操作,我想按社区过滤。给定一个评论对象,我可以通过 获取用户对象comment.user
,但我不能超越它(即,类似的东西comment.user.geography(0).community
不起作用)。
似乎这个对象链接是 rails 的一个关键特性,但它是否适用于 has_many :through 关联?给定我的示例,是否可以通过使用对象链接从评论对象中获取社区对象,或者在给定评论对象时,我是否需要编写 SQL 来获取用户以外的任何内容?