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!