在 ruby on Rails 中,当记录有多个标签时如何按标签对记录进行分组
我正在使用 Rails 3.0 和acts_as_taggable_on gem。我有一个糖果模型,糖果可以有多个口味标签。假设
Candy1.tags #['apple', 'orange']
Candy2.tags #['orange', 'banana']
Candy3.tags #['apple', 'kiwi']
我想要一个标签列表,其下方有相关糖果,如下所示:
Apple
- Candy1
- Candy3
Orange
- Candy1
- Candy2
...等。
我已经尝试过,
Candy.all.group_by{ |candy| candy.tags }
但将标签数组视为单个实体,返回如下内容:
['apple', 'orange']
- Candy1
['orange', 'banana']
- Candy2
缺少 group_by_each 方法,最好的方法是什么来完成这个? 另一个 Stack Overflow 问题解释了如何使用简单的哈希在内存中执行此操作,但是我想知道是否有一种更面向数据库的方法来处理 ActiveRecord 关联。
I'm using Rails 3.0 and the acts_as_taggable_on gem. I have a Candy model and candies can have multiple tags for flavors. Let's say
Candy1.tags #['apple', 'orange']
Candy2.tags #['orange', 'banana']
Candy3.tags #['apple', 'kiwi']
I want a list of tags with associated candies below them, like so:
Apple
- Candy1
- Candy3
Orange
- Candy1
- Candy2
...etc.
I've tried
Candy.all.group_by{ |candy| candy.tags }
but that treats the array of tags as a single entity, returning something like this:
['apple', 'orange']
- Candy1
['orange', 'banana']
- Candy2
Lacking a group_by_each method, whats the best way to accomplish this? Another Stack Overflow question explains how to do this in memory with simple hashes, but I wonder if there's a more database-oriented way to do it with ActiveRecord associations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以迭代糖果并将它们存储在标签上的哈希基础上:
最后您将得到:
希望这对您有帮助
You can iterate over the candies and store them on a hash base on the tag:
At the end you will get:
Hope this helps you
现在
candies
是一个像这样的哈希:你可以很好地迭代它:
Now
candies
is a hash like this:Which you can iterate over nicely:
在rails api文档中,group_by用于收集可枚举的。我认为你需要尝试一个更经典的数组迭代器,如下所示,因为你
在views/candy/index.html.erb中
有字符串数据让我知道它是否有效
In rails api documentation that group_by is for collecting enumerable. I think you need to try a more classic array iterator like the following since you've strings data
in views/candy/index.html.erb
Let me know if it works