根据上下文返回所有标签 - ActsAsTaggableOn
我正在使用 Rails gem 充当可标记的角色,并在两个上下文中标记帖子:标签和主题。
要返回迄今为止用于帖子的所有主题标签的哈希值,我可以使用以下代码:
Post.tag_counts_on(:topics)
但是,我已经创建了一定数量的设置主题标签,并且如果其中一些主题标签当前未用作帖子上的标签,那么上面的代码不会返回上述主题。
我想知道是否有一种方法可以根据上下文返回所有相关标签 - 我希望有一个解决方案:
topics = Tag.topics
为了实现该解决方案,我创建了一个 Tag.rb 模型:
class Tag < ActiveRecord::Base
has_many :relationship_topics, :foreign_key => "topic_followed_id", :dependent => :destroy
has_many :topic_followers, :through => :relationship_topics, :source => :topic_follower
end
这里我有一些代码允许对于以下主题,仅此而已。
有谁知道我如何根据上下文返回所有标签?
I'm using the rails gem acts-as-taggable on, and am tagging posts on two contexts: tags and topics.
To return a hash of all the topics tags used so far for posts I can use the code:
Post.tag_counts_on(:topics)
However, I have created a certain number of set topics tags, and if some of these topics tags aren't currently being used as tags on posts, then the code above doesn't return the said topics.
I am wondering if there is a way to return all the relevant tags based on context -- I was hoping for a solution along the lines of :
topics = Tag.topics
To implement the solution, I created a Tag.rb model:
class Tag < ActiveRecord::Base
has_many :relationship_topics, :foreign_key => "topic_followed_id", :dependent => :destroy
has_many :topic_followers, :through => :relationship_topics, :source => :topic_follower
end
Here I have some code to allow for following topics, but nothing more.
Does anyone know how I could return all the tags based on context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我从未使用过 acts-as-taggable-on 但快速浏览了一下代码建议,你可以这样做:
你应该看看 ActsAsTaggableOn::标记, ActsAsTaggableOn::Tag 和 db/migrations 文件夹中的迁移文件,以了解如何进行操作。
如果您不需要计数,只需要标签名称:
我希望这能回答您的问题。
I have never used acts-as-taggable-on but a quick browse through of the code suggests, you can do:
You should probably take a look at ActsAsTaggableOn::Tagging, ActsAsTaggableOn::Tag and the migration file in your db/migrations folder to figure out how you can go about it.
If you don't want the count, only the tag names:
I hope that answers your question.
使用
Model.tag_counts
(来自 使用acts-as-taggable-on如何在我的应用程序中找到顶部(例如10个)标签?):Use
Model.tag_counts
(from Using acts-as-taggable-on how do I find the top, say 10, tags in my app?):这对我来说效果最好:
使用标记上下文进行
joins
或includes
时的一个限制是您只能看到活动的主题。您无法加载主题列表并使用此查询显示它们。请参阅示例:没有标记上下文
有
主题
的标记上下文This worked best for me:
One limitation when doing
joins
orincludes
with a tagging context is that you will only see topics that are active. You cannot load up a topic list and have them show up using this query. See examples:Without tagging context
With taggings context of
topics
方法很简单:
The method is very simple: