Rails 通过*所有*关联的tags.id 查找

发布于 2024-08-27 08:10:02 字数 859 浏览 4 评论 0原文

假设我有一个模型 Taggable has_many 标签,我如何通过关联标签的 taggable_id 字段找到所有 taggable?

Taggable.find(:all, :joins => :tags, :conditions => {:tags => {:taggable_id => [1,2,3]}})

结果如下:

SELECT `taggables`.* FROM `taggables` INNER JOIN `tags` ON tags.taggable_id = taggables.id WHERE (`tag`.`taggable_id` IN (1,2,3))

语法令人难以置信,但不符合我的需求,因为生成的 sql 返回任何具有任何、部分或全部标签的可标记对象。

如何找到具有字段 taggable_id 值为 1、2 和 3 的相关标签的可标记项?

感谢您的任何建议。 :)

更新:

我已经找到了一个解决方案,如果他们最终在这里,我将向其他人发布该解决方案。另外,为了引起其他人的关注,我很乐意收到他们的改进建议。 :)

Taggable.find(:all, :joins => :tags, :select => "taggables.*, tags.count tag_count", :conditions => {:tags => {:taggable_id => array_of_tag_ids}}, :group => "taggables.id having tag_count = #{array_of_tag_ids.count}"))

Say I have a model Taggable has_many tags, how may I find all taggables by their associated tag's taggable_id field?

Taggable.find(:all, :joins => :tags, :conditions => {:tags => {:taggable_id => [1,2,3]}})

results in this:

SELECT `taggables`.* FROM `taggables` INNER JOIN `tags` ON tags.taggable_id = taggables.id WHERE (`tag`.`taggable_id` IN (1,2,3))

The syntax is incredible but does not fit my needs in that the resulting sql returns any taggable that has any, some or all of the tags.

How can I find taggables with related tags of field taggable_id valued 1, 2 and 3?

Thanks for any advice. :)

UPDATE:

I have found a solution which I'll post for others, should they end up here. Also though for the attention of others whose suggestions for improvement I'd happily receive. :)

Taggable.find(:all, :joins => :tags, :select => "taggables.*, tags.count tag_count", :conditions => {:tags => {:taggable_id => array_of_tag_ids}}, :group => "taggables.id having tag_count = #{array_of_tag_ids.count}"))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

默嘫て 2024-09-03 08:10:02

你的问题有点令人困惑(“标签”似乎被使用了很多:)),但我认为你想要我需要的同样的东西此处

Taggable.find([1,2,3], :include => :tags).tags.map { |t| t.taggables }

或者(如果您希望结果是唯一的,您可能会这样做):

Taggable.find([1,2,3], :include => :tags).tags.map { |t| t.taggables }.flatten.uniq

这会获取与 ids 1 的可标记项具有相同标记的所有可标记项,2,和3。这是你想要的吗?

Your question is a bit confusing ('tags' seemed to be used quite a bit :)), but I think you want the same thing I needed here:

Taggable.find([1,2,3], :include => :tags).tags.map { |t| t.taggables }

or (if you want the results to be unique, which you probably do):

Taggable.find([1,2,3], :include => :tags).tags.map { |t| t.taggables }.flatten.uniq

This gets at all the taggables that have the same tags as the taggables that have ids 1,2, and 3. Is that what you wanted?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文