获取所有贴有任何属于用户兴趣的帖子

获取所有贴有任何属于用户兴趣的帖子

问题描述:

我正在制作一个网站,在注册后用户选择他们的兴趣是什么。所以用户只能看到与他们相关的帖子。用户和兴趣之间的关系(在我的例子中)通过连接表是一种多对多的关系。另外,用户可以创建帖子并向帖子添加标签。一个标签可以有很多帖子。所以标签和帖子之间的关系通过连接表是多对多的关系。在users表中我有一个tag_ids列存储一个集合。与posts表相同,我有一个tag_ids列存储集合。获取所有贴有任何属于用户兴趣的帖子

在我的用户模型我有

has_many :user_tags 
has_many :tags,:through => :user_tags 

在我的岗位模型我有

has_many :post_tags 
has_many :tags,:through => :post_tags 

如果我不喜欢的东西current_user.tag_ids我会得到类似[2, 3]。如果我像Post.first.tag_ids那样做,我会得到类似[2, 4, 7]的东西。希望你能得到一般图片。那么,如何在使用活动记录的帖子tag_ids列中提取当前用户的任一tag_id的所有帖子(如果可能的话)中提取所有帖子。谢谢

+0

只是为了澄清,你问如何找到current_user.tag_ids和post.tag_ids之间的通用tag_ids? – ZubatMan

+1

是的,然后显示所有有他们tag_id的职位 –

我能想到的最简单的方法是简单地查询current_user和Post的tag_id,找到两者之间的任何常见tag_id,然后根据这些id查询实际标记的数据库。下面是一个基本的演练:

# Get the current_user's tags 
user_tags = current_user.tag_ids 

# Map over all of the existing posts and grab all tag_ids 
# Once you have them, flatten the result into a single array and make all values unique 
post_tags = Post.all.map { |p| p.tag_ids }.flatten.uniq 

# Find any common tags using '&' 
common = user_tags & post_tags 

然后你可以去在产生共同阵列,发现每个相关标签使用枚举.map方法:

# Map over common and find the relevant tags - return them in a new array 
common.map do { |t_id| Tag.find(t_id) } 

这将让您实际的标签对象。

+0

我想看看职位模型。不是特定的帖子。我使用Post.first.tag_ids只是为了让你了解一条记录返回的内容。我想要获取所有帖子,然后在显示页面中循环显示 –

+0

因此,您想要在current_user的tag_id和任何现有帖子中的tag_id之间使用通用标签吗? – ZubatMan

+0

Yeahp ...多数民众赞成在它......会很高兴,如果你能帮我弄明白 –