我正在制作一个网站,用户注册后可以选择他们的兴趣。因此,用户只能看到与他们相关的帖子。用户和兴趣(在我的例子中是标签)之间的关系是通过连接表的多对多关系。此外,用户可以创建帖子并向帖子添加标签。并且一个标签可以有很多帖子。因此,标签和帖子之间的关系是通过连接表的多对多关系。在 users
表中,我有一个 tag_ids
列,用于存储集合。与 posts
表相同,我有一个 tag_ids
列来存储集合。
在我的用户模型中,我有
has_many :user_tags
has_many :tags,:through => :user_tags
在我的 Post 模型中,我有
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_ids 的所有帖子。谢谢
最佳答案
我能想到的最简单的方法是简单地查询 current_user 和 Post 的 tag_ids,找到两者之间的任何公共(public) tag_ids,然后根据这些 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
然后,您可以检查生成的公共(public)数组并使用枚举器 .map
方法查找每个相关标签:
# Map over common and find the relevant tags - return them in a new array
common.map do { |t_id| Tag.find(t_id) }
这将为您提供实际的 Tag 对象。
关于sql - 获取所有已标记为属于用户的任何兴趣的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36774900/