【问题标题】:How to setup multiple has_many through relationships in Rails3 dependent on field in joining table如何通过 Rails3 中依赖于连接表中的字段的关系设置多个 has_many
【发布时间】:2011-04-29 21:30:52
【问题描述】:

这可能真的很简单,但我仍然处于起步阶段,似乎无法找出正确的短语来输入 Google 以找到答案。

我有一个非常简单的 has_many through 关系,如下所述:

用户
-user_id
-名称

文章
- article_id
- 标题

Article_Relationship
- 用户 ID
- article_id
- 关系类型

在关系类型上,它可以是一个字符串或整数来表示一种关系类型,比如喜欢、最近查看、写过等等。如何设置多个 has_many :articles, :through => :article_relationships 以便我可以通过 user.recently_viewed、user.favorite 等轻松访问特定类型关系的文章?

非常感谢。

【问题讨论】:

    标签: ruby-on-rails activerecord has-many-through


    【解决方案1】:

    你在正确的轨道上,但你只需要使用范围:

    class Article < ActiveRecord::Base
      # Here RECENTLY_VIEWED_TYPE refers to the type of relationship, whatever
      # that constant is defined as.
      scope :recently_viewed,
        where('article_relationships.relationship_type=?', RECENTLY_VIEWED_TYPE)
    end
    

    然后你可以直接从用户那里访问这个:

    @user.articles.recently_viewed.all
    

    【讨论】:

      【解决方案2】:

      您可以将:conditions:through 选项一起传递给has_many。您还可以将关联命名为不同的名称。因此,您可以执行以下操作:

      class User < ActiveRecord::Base
        has_many :article_relationships
        has_many :articles, :through => :article_relationships
      
        has_many :recently_viewed_articles, :class_name => 'Article', :through => :article_relationships, :conditions => ['article_relationships.relationship_type = ?', 1]
      
        has_many :favorite_articles, :class_name => 'Article', :through => :article_relationships, :conditions => ['article_relationships.relationship_type = ?', 2]
      end
      

      您可能需要稍微尝试一下传递给has_many 的选项,但您明白了。

      【讨论】:

      • 这似乎运作良好!谢谢!除了其余的 has_many 选项之外,我还必须添加 :source => 'article' ,否则它也不知道我指的是什么,但一旦完成,一切顺利!
      猜你喜欢
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 2014-09-04
      • 2016-12-21
      • 2019-08-14
      • 2019-11-09
      相关资源
      最近更新 更多