Rails使用某些标签查找所有post而不使用acts_as_taggable

所以我正在努力学习铁轨,我还不想作弊。

发布模式:

class Post  :features end 

标签型号:

 class Tag  :features end 

连接表:

 class Feature < ActiveRecord::Base belongs_to :tag belongs_to :post end 

我已经知道如何将post与标签相关联: Post.find_by_id(1)<< Tag.first

现在,我一直在寻找带有某些标签的post。 如何搜索具有以下一个或多个标签的所有post: “游泳”,“跑步”,“赚钱”

Post1包含标签:“骑自行车”,“攀岩”,“游泳”

Post2包含标签:“青蛙”,“鱼”

Post3包含标签:“赚钱”,“游泳”,“骑自行车”,“爱”

Post4包含标签:“游泳”

我希望首先显示符合用户兴趣的post。

例如:用户应按此顺序查看post列表…. post3,post1,post4。 如果这太难了,我猜测找到所有带有确切标签的post的方法就足够了。

你应该能做到的

 @tag.posts 

有没有理由你没有使用has_and_belongs_to_many关系?

更新:

根据你的评论:

 tag_ids = [1, 2, 3] # aka the IDs for tags ["swimming", "running", "making money"] matches = {} @posts.each do |post| count = 0; post.tags.each do |tag| count += 1 if tag_ids.include? tag.id end matches[count] ||= [] matches[count] << post end 

可能会进行一些优化,但matches将根据匹配的数量包括与键中所请求标记匹配的所有post。 这也应该在Posts模型的类方法中而不是在控制器中。