Rails 3:如何进行HABTM关系的数据库调用
我在帖子模型、流派模型和流派_帖子模型之间设置了 HABTM 关系。我的流派模型有一个 name:string 属性,其中包含“惊悚片”、“西部片”、“恐怖片”、“动作片”、“喜剧片”等名称,当用户创建帖子时,他们可以向帖子添加 1 个或多个流派。
我需要能够按特定类型列出用户的所有帖子,以便他们可以轻松地在所有类型为“西方”的帖子和所有类型为“动作”的帖子之间来回切换。
Post.last.genres 为我提供了帖子的流派,但是对于用户帖子的数组(例如 @user.posts )我该如何做?然后指定具体的流派名称?
这是做这类事情最明智的方法吗?
I setup a HABTM relationship between my post model, genre model, and genres_posts model. My genre model has a name:string attribute which consists of names like 'thriller' 'western' 'horror' 'action' comedy' etc, when a user creates a post they can add 1 or more genres to the post.
I need to be able to list all of a user's posts by the specific genre, so they can easily switch back and forth between all their posts with genre 'western' and all the posts with genre 'action'.
Post.last.genres gives me the post's genres, but how would I do it for an array of a user's posts such as @user.posts ?? and then specify the specific genre name?
Is this the smartest way to do this type of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
除了ctcherry的回答之外,这也是可能的:
In addition to ctcherry's answer, this is also possible:
我假设您将在某个地方有一个流派列表,因此您可以先获取流派,然后获取按用户过滤的帖子:
I assume your going to have a list of Genres somewhere, so you can get the Genre first, then get it's Posts filtered by user: