【问题标题】:Rails ActiveRecord polymorphic associated relationshipsRails ActiveRecord 多态关联关系
【发布时间】:2014-06-26 22:28:18
【问题描述】:

我已经制作了一个带有标签的 Rails 应用程序,我可以用它来标记各种其他模型,但是与正常的多态关系不同,每个标签名称只有 1 个标签记录,然后我使用了一个名为 " TagRealtionship" 以跟踪已标记的内容并具有标记 ID 和可标记 ID 以及可标记类型。现在我正在使用标签和博客模型。模型如下所示:

class Blog < ActiveRecord::Base
    has_many :tag_relationships, :as => :tagable, dependent: :destroy
    has_many :tags, :through => :tag_relationships

class Tag < ActiveRecord::Base
    has_many :tag_relationships, dependent: :destroy

class TagRelationship < ActiveRecord::Base
    belongs_to :tagable, :polymorphic => true
    belongs_to :tag

我正在尝试做的是提取与某个标签匹配的所有博客。如果我采用标签模型并运行此查询...

@tag.tag_relationships.where(tagable_type: "Blog")

我得到这样的关联关系

=> #<ActiveRecord::AssociationRelation [#<TagRelationship id: 1, tag_id: 1, tagable_id:        108, tagable_type: "Blog", created_at: "2014-06-26 18:45:50", updated_at: "2014-06-26 18:45:50">, #<TagRelationship id: 2, tag_id: 1, tagable_id: 102, tagable_type: "Blog", created_at: "2014-06-26 18:46:10", updated_at: "2014-06-26 18:46:10">, #<TagRelationship id: 3, tag_id: 1, tagable_id: 127, tagable_type: "Blog", created_at: "2014-06-26 20:28:29", updated_at: "2014-06-26 20:28:29">]>

如果我获取其中一条记录并在其上调用 .tagable 并且可以获取博客文章,但我想知道是否有一种方法可以查询并获取所有匹配博客文章的 ActiveRecord 集合。我知道如果我这样做 .map(&:tagable) 它将给我一个博客帖子数组,但我需要 Active Record 集合,以便我可以进一步过滤它并对帖子进行分页。

【问题讨论】:

    标签: sql ruby-on-rails postgresql activerecord ruby-on-rails-4


    【解决方案1】:

    换句话说,您想获取特定标签的博客文章列表,对吗?

    # Find all blog posts where tag id = 1
    Blog.includes(:tags).where(tags: {id: 1})
    

    您还可以向 Blog 模型添加范围以使其更易于使用:

    class Blog < ActiveRecord::Base
      has_many :tag_relationships, :as => :tagable, dependent: :destroy
      has_many :tags, :through => :tag_relationships
    
      scope :tagged_with, -> (tag) {
        includes(:tags).where(tags: {id: tag.id})
      end
    end
    

    并像这样使用新的范围:

    tag = Tag.find(1)
    Blog.tagged_with(tag)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多