2013-06-29 27 views
0

在Ruby on Rails中,我正在做一些涉及可以標記的帖子,比如說5個標籤。我希望能夠通過標籤爲帖子編制索引。在Rails中,可以通過多達5個標籤搜索帖子

與當前類似模型的方式:

Post attributes include: 
    tag1 
    tag2 
    tag3 
    tag4 
    tag5 

然後,每當你想找到一個標籤後,你做這樣的事情:

posts = Post.find_all_by_tag1(name) 
posts2 = Post.find_all_by_tag2(name) 
posts3 = Post.find_all_by_tag3(name) 
posts4 = Post.find_all_by_tag4(name) 
posts5 = Post.find_all_by_tag5(name) 
posts.concat posts2 
posts.concat posts3 
posts.concat posts4 
posts.concat posts5 

這是最好的方法去做吧?

回答

0

我建議做一個表標記,屬性是名稱,product_id。 當你的標籤可以在另一個類中使用。請使用多態關聯,屬性是name,tagable_id,tagable_type。

詳細瞭解concept polymorphic和例子practice polymorphic

0

不,那將需要5個查詢,並可能導致重複的帖子!

1)有一個Tag模型,has_many:posts。每次添加帖子時,find_or_create都會爲帖子上的每個標籤添加一個標籤,然後關聯該帖子。 2)查找一組標籤的所有帖子的東西,如:

SELECT posts.* FROM posts 
INNER JOIN tags on tags.post_id = posts.id 
AND tags.tag IN ('foo', 'bar', 'baz') 

這將找到它可以在你的IN子句中加入到標籤中的至少一個的所有帖子。這解決了多個查詢和重複發佈的問題,並且不需要在可標記模型上重複。正如指出的那樣,ActsAsTaggableOn gem爲你解決了這個問題,但是你應該試着理解它在封面下的做法。