【问题标题】:Rails 3: Object chaining with has_many :through associationsRails 3:使用 has_many 进行对象链接:通过关联
【发布时间】: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_idcommunity_id)。

我有一个列出所有 cmets 的索引操作,我想按社区进行过滤。给定一个评论对象,我可以通过comment.user 获取用户对象,但我无法超越此链接(即,comment.user.geography(0).community 之类的东西不起作用)。

似乎这个对象链接是 rails 的一个关键特性,但它是否适用于 has_many :through 关联?以我的例子为例,是否可以通过使用对象链接从评论对象中获取社区对象,或者在给出评论对象时我是否需要编写 SQL 来获取用户以外的任何内容?

【问题讨论】:

    标签: ruby-on-rails-3 associations


    【解决方案1】:

    由于用户与多个社区相关联,您需要告诉 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.
    

    【讨论】:

      【解决方案2】:

      我认为您不需要地理表。

      试试

      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

      【讨论】:

      • 谢谢,但我需要选择属于多个社区的用户。我相信您描述的模型将用户限制在一个社区(如果我错了,请纠正我)。
      • 哎呀,你是对的。我看错了。我想如果您只是将 Community.rb 中的行更改为 has_many :users, :through =&gt; :geographies。然后你可以说像@comment.user.communities 这样的东西来获取所有用户的社区,并从那里指定
      • 感谢管家。 Salil 是对的,我需要从所有返回的社区(第一个、最后一个等)中选择一个社区。此外,我可以使用您描述的链访问社区,即使不包括 :through :geographies 行,它似乎也可以正常工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2013-05-06
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多