Acts-as-taggable-on 按上下文查找所有标签 [英] Acts-as-taggable-on find all tags by context

查看:45
本文介绍了Acts-as-taggable-on 按上下文查找所有标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在为我的 rails 应用程序搜索标记 gem 之后,我发现了惊人的 acts-as- 可标记 宝石.安装它并玩转我发现它将所有标签保存在一个标签数据库中,该数据库只保存 Tag.name 而没有上下文,而不是上下文保存在 :through 关系数据库( taggings )中.对于大多数目的,我可以看到这是完美的.除了我的应用程序,我希望能够为用户提供基于预先存在的标签(例如不允许他们创建自己的标签)和 acts-as-taggable 不能在一个内置的上下文中搜索所有标签(例如,如果我要呈现自动完成在标签数据库中,我将包含我的应用程序中的所有标签,这不是我想要的)

So after searching for a tagging gem for my rails app I found the amazing acts-as-taggable gem. Installing it and playing around I discovered that it keeps all the Tags inside a tag db which just holds the Tag.name without the context, instead the context is held in the :through relationship db ( taggings ). For most purposes I can see this being perfect. Except with my app I want to be able to offer the user the ability to tag based on an pre-existing tags ( eg not allow them to create their own ) and acts-as-taggable doesn't have the ability to search all tags within one context built in ( eg, if I were to present an auto-completion of the tag db I would have all the tags in my app included which is'nt what I want )

下面的方法是我刚刚充实的内容,看看它是否有效(确实如此),但我想知道我是否遗漏了 作为可标记行为.我的意思是我看不到任何提供这种方法的地方?

The method below is what I just fleshed out to see if it would work ( which it does ) but I wondered if I was missing something with acts-as-taggable. I mean I can't see anywhere that offers this kind method?

<% ActsAsTaggableOn::Tagging.find_all_by_context("tags").each do |tagging| %>
  <%= tagging.tag %>
<% end %>

例如,如果 acts-as-taggable 不这样做,这是最好的方法吗?感觉有点性能不佳,我会更好地执行自定义 SQL 查询而不是通过 acts 进行路由-as-taggable?

If for instance acts-as-taggable doesn't do this, is this the best way to do this? It feels a little non performant, Would I be better doing a custom SQL query instead of routing through acts-as-taggable?

如果它有帮助,那就是我的日志尾部:

If it helps at all heres a tail of my log:

Started GET "/users" for 127.0.0.1 at 2011-01-04 14:46:20 +0000
Processing by UsersController#index as HTML
SQL (0.5ms)   SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
User Load (0.1ms)  SELECT "users".* FROM "users"
ActsAsTaggableOn::Tagging Load (0.5ms)  SELECT "taggings".* FROM "taggings" WHERE ("taggings"."context" = 'languages')
ActsAsTaggableOn::Tag Load (0.1ms)  SELECT "tags".* FROM "tags" WHERE ("tags"."id" = 2) LIMIT 1
Rendered users/index.html.erb within layouts/application (10.4ms)

推荐答案

您也可以使用如下语句:

You could also use a statement like the following:

# Returns all the tags for the specified model/context with a count >= 1
@tags = YourModel.tag_counts_on(**context**)

添加限制和订单:

# Get the top 5 tags by count
@tags = YourModel.tag_counts_on(**context**, :limit => 5, :order => "count desc")

使用从 tag_counts_on

tag.count

这篇关于Acts-as-taggable-on 按上下文查找所有标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆