我有一个帖子,可以有标签,标签有一个类别。现在我需要创建一个"发布"的范围。只有在每个可用类别中都包含标记时,才能发布帖子。所以换句话说。如果数据库包含4个tagcategory记录,则帖子应该在所有这4个类别中都有标记,以便被视为已发布。
帖子有很多标签(通过tag_categories)。标签属于tag_category。标签类别有很多标签
在帖子实例上,我可以轻松创建这样的方法:
def has_tags_in_all_categories?
#select all category id's
category_ids = TagCategory.pluck(:id)
#select all post tag id's
tag_ids = self.tags.pluck(:tag_category_id)
#create a new array with the category ids from the post.tags subtracted from all category ids
remaining = category_ids.reject{|x| tag_ids.include? x}
#if id's are left in the array -> Not all categories are filled in.
remaining.empty?
end
但要在一个页面上显示所有已发布的帖子,我需要创建一个范围。循环遍历所有帖子并应用此方法,显然会导致许多不确定的数据库查询。
有人可以帮我解决问题吗?
class Post < ActiveRecord::Base
def self.published
find(:all) #No clue here
end
end
数据库(对不起,我不知道怎么做这个幻想):
posts
id
title
posts_tags
post_id
tag_id
tags
id
tag_category_id
name
tag_categories
id
name