Rails 通过*所有*关联的tags.id 查找
假设我有一个模型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题有点令人困惑(“标签”似乎被使用了很多:)),但我认为你想要我需要的同样的东西此处:
或者(如果您希望结果是唯一的,您可能会这样做):
这会获取与 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:
or (if you want the results to be unique, which you probably do):
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?