sql - Rails ActiveRecord 多态关联关系

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

我制作了一个 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 集合,这样我可以进一步过滤它并对文章分页。

最佳答案

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

# 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)

关于sql - Rails ActiveRecord 多态关联关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24441237/

相关文章:

javascript - 从 View 中设置一个 cookie,然后从 Rails 中的 Controller 读取它

mysql - ORDER BY 随机子级别的 SQL 语法?

mysql - 使用以相同字段开头的 GROUP BY 优化多个查询

php - 使用字符串作为条件计算 SQL 中的行数

sql - 将 nvarchar 数据类型转换为日期时间数据类型导致值超出范围

postgresql - 如何从 postgresql 函数或触发器发送一些 http 请求

sql - 不按顺序选择

mysql - 子查询只返回一个值

ruby-on-rails - 不同类型内容的不同部分

ruby-on-rails - Rake 中止...表 'users' 已存在