1

我现在计划这个功能很长时间了,但我真的无法开始使用它,因为我不知道如何用代码来表达它。有时,当我认为我明白了自己想要什么时,我突然又被困住了,一切都变得毫无意义。

我有标签和标签,所以通过与文章的关系有一个 has_many。您可以调用 article.tags 和 tag.articles。

现在,每个标签都有自己的显示页面,基本上就像 stackoverflow。在这个展示网站上,我想列出相关标签等。我对这些相关标签的处理方法是,它应该是那些标签,它们最常被标记在一篇文章中,它被标记为 show 标签。我希望这有点道理。

示例:我在 /tags/obama,所以相关标签应该是文章中最常使用的标签,包括标签 obama。例如,如果我有 4 篇文章,其中 3 篇包含“obama”,并且所有这 3 篇都包含标签“united_states”,那么与标签“obama”最相关的标签将是“united_states”。对不起,如果我罗嗦..

我什至不确定这是否是查找相关标签的最佳方法,但这个想法对我来说很好。但是,我无法实现它。

首先,我需要获取所有包含显示标签的文章。所以tag.articles。但下一步是什么?

tag.articles.each do |article|
  article.tags

...我只是在这一点上感到困惑。

4

1 回答 1

1

我认为解决这个问题的最好方法是在标签之间建立多对多关系,所以一个标签可以有很多标签。然后在两个标签之间的关系中,存储它们一起出现的实例数。

每次标签出现在同一篇文章中时,您也可以简单地创建一个新的标签到标签连接。然而,这将在数据库中创建一些冗余。

如果你不想引入另一个表,你可以按照你开始的方式让它工作,除非它可能非常慢,即使是相当少量的标签。但是,如果您无法建立标签到标签的连接,我会这样做:

hash_storage = Hash.new(0) #0 is the default value
tag.articles.each do |article|
   if article.tags.each do |t|
      #we now know that this tag "t" is in the same article as our original tag
      if t!=tag #we don't care if t actually the same as our original tag
          hash_storage[t]+=1
      end
   end
end
#Now, this is a bit messy, but we need to sort the hash.
ordered_tags = hash_storage.map{|k,v| [v,k]}.sort.reverse.map{|a,b| b} #there might be a smarter way of doing this. 

ordered_tags.each do |t|
  #do whatever. the tags should now  be ordered by their relative frequence of occurrance together with the initial tag.
end    

希望这可以帮助 :)

于 2012-07-29T15:50:29.837 回答