【发布时间】:2012-06-30 23:58:25
【问题描述】:
我正在尝试了解如何在 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
用户可以发布cmets,并通过地理表关联到一个或多个社区(地理表存储user_id和community_id)。
我有一个列出所有 cmets 的索引操作,我想按社区进行过滤。给定一个评论对象,我可以通过comment.user 获取用户对象,但我无法超越此链接(即,comment.user.geography(0).community 之类的东西不起作用)。
似乎这个对象链接是 rails 的一个关键特性,但它是否适用于 has_many :through 关联?以我的例子为例,是否可以通过使用对象链接从评论对象中获取社区对象,或者在给出评论对象时我是否需要编写 SQL 来获取用户以外的任何内容?
【问题讨论】:
标签: ruby-on-rails-3 associations