0

我有其中有许多故事使用SQL或狮身人面像

每个故事都有属于许多标签(使用行为-AS-加标签上)

每一个应用程序,我怎么能找到相关的标记记录故事也通过思考索引sphinx

我需要的是通过标签查找彼此相关的故事,并按照他们共享的标签数量排序。

鉴于以下数据:

 
Story #1 tagged with a,b,c,d 
Story #2 tagged with a 
Story #3 tagged with b,a 
Story #4 tagged with d,c,b 

Story.find(1).related #=> Story 4, Story 3, Story 2 


...的顺序

可有人建议这一个好方法?我想有一个简单的方法来做到这一点使用SQL,但我不是一个SQL超人

感谢

回答

1

这应该做到这一点。 Story.find(1).find_related_tags

+0

尼斯,我不得不去看看这个宝石。 – Dex 2011-06-16 02:29:33

+0

Dhruva - 谢谢,你的回答基本上是正确的。为了我想要做的事情,我不得不稍微扩展它,所以我已经发布了我的解决方案 – bodacious 2011-06-24 08:14:34

+0

很高兴帮助:) – 2011-06-24 09:13:52

0

不知道你的数据库看起来完全像什么,但我会认为它看起来像:

stories: 
    id 
    content 

tags: 
    id 
    name 

story_tags: 
    story_id 
    tag_id 

尝试先运行一个查询只是为了看看它给你预期的结果:

SELECT stories.id, COUNT(*) AS ordering FROM stories 
    INNER JOIN story_tags ON story_tags.story_id = stories.id 
    WHERE story_tags.tag_id IN ('id of tag a', 'id of tag b', 'id of tag c', 'id of tag d') 
    GROUP BY stories.id 
    ORDER BY ordering DESC; 
0

这里就是我最终没有解决这一个:

class MyModel < ActiveRecord::Base 

    scope :related_to, lambda { |record| 
    joins(:tags,:taggings). 
    where(record.class.model_name == self.model_name ? ["#{table_name}.id != ?", record.id] : ""). 
    where("tags.id IN (SELECT taggings.tag_id from taggings where taggable_type = ? and taggable_id = ?)", record.class.model_name, record.id). 
    order("count(DISTINCT(tags.id)) DESC"). 
    group("#{table_name}.id") 
    } 

end 

这意味着我可以:

 
    @blog_post.related_to(@ad) # => returns all @blog_posts with the same tags as @ad, in order of the number of tags they share!