如何跨虚拟属性进行查询?

时间:2015-03-12 09:36:34

标签: ruby-on-rails ruby-on-rails-4 activerecord virtual-attribute

我有一个Node模型,它有一个虚拟属性user_tags

这就是它在控制台上的样子:

[42] pry(main)> n = Node.first
  Node Load (0.5ms)  SELECT  "nodes".* FROM "nodes"   ORDER BY "nodes"."id" ASC LIMIT 1
=> #<Node id: 6, name: "10PP Form Video", family_tree_id: 57, user_id: 57, media_id: 118, media_type: "Video", created_at: "2015-03-09 20:57:19", updated_at: "2015-03-09 20:57:19", circa: nil, is_comment: nil>
[43] pry(main)> n.user_tags
  ActsAsTaggableOn::Tag Load (0.3ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND "taggings"."context" = 'user_tags'  [["taggable_id", 6], ["taggable_type", "Node"]]
=> [#<ActsAsTaggableOn::Tag id: 6, name: "danny@test.com", taggings_count: 1>, #<ActsAsTaggableOn::Tag id: 4, name: "gerry@test.com", taggings_count: 1>]

我想要做的是在scope模型上创建Node,以映射到user_tags的节点。即!user_tags.empty?

我该怎么做?

1 个答案:

答案 0 :(得分:2)

scope :with_tags, ->() { joins(:tags).uniq }

您不能使用where,因为标签存储在与您的模型不同的单独表格中 - 您必须先与其他表格建立联接。现在可爱的部分 - joins执行INNER JOIN,这意味着它不会加载在另一个表中没有匹配记录的模型。现在剩下的就是摆脱重复(如果你有带有n个标签的模型,JOIN将返回该记录n次)