1

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

后模型:

class Post < ActiveRecord::Base
    has_many :features
    has_many :tags, :through => :features
end

标签型号:

class Tag < ActiveRecord::Base
    has_many :features
    has_many :posts, :through => :features
end

连接表:

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

我已经知道如何通过以下方式将帖子与标签相关联:Post.find_by_id(1) << Tag.first

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

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

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

Post3包含标签:“赚钱”、“游泳”、“骑车”、“爱情”

Post4 包含标签:“游泳”

我希望最符合用户兴趣的帖子首先出现。

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

4

1 回答 1

0

你应该能够做到

@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随后会根据匹配的数量在键中包含与请求的标签匹配的所有帖子。这也应该放在 Posts 模型的类方法中,而不是控制器中。

于 2011-03-03T04:38:49.753 回答