按“投票”数量显示帖子记录在单独的表中
我是 Rails 新手,所以放轻松。我创建了一个博客,还为用户创建了表示他们“喜欢”特定帖子的功能。我实现此目的的方法是使用帖子表和单独的表“投票”。当用户单击“喜欢”按钮时,它会将记录发送到“投票”表,其中值为“1”和特定的帖子 ID。
我想在侧边栏中显示“最喜欢”的帖子。我该如何调用这样的东西呢?我想显示 post_title 和“投票”数量,也就是说,我想以某种方式查询“投票”表中记录最多的 post_id 并按降序显示它们。
我希望这是一个简单的问题。
I am new to Rails so go easy. I have created a blog and also created the ability for users to indicate they "like" a particular post. The way I am implementing this is by using the post table and a separate table 'vote'. When the user clicks the "like" button it sends the record to the 'vote' table with a value of '1' and the particular post id.
I would like to display the "most liked" posts in the sidebar. How do I go about calling such a thing. I would like to display the post_title and the number of 'votes', that is, I would like to somehow query the 'vote' table for the post_id's that have the most records and display them in descending order.
I hope this is an easy question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有多种方法可以实现这一点,但最通用且最接近 Rails 的方法可能是创建一个带有排名方法的模块,然后让任何可以“喜欢”的类或关联扩展该模块。
这可以让你做一些事情,比如......
如果你稍后需要,你可以向模块添加方法来查看,例如,特定帖子有多少票。您还可以将
Vote
中的post_id
更改为target_id
并使其成为多态关联,然后您可以使用您的 Likable 模块来投票任何东西,而不仅仅是帖子(如果您这样做,您需要概括调用以在most_liked中查找)。There are several ways to accomplish this, but probably the most versatile and Rails-ish would be to create a module with a method to do the ranking, and then have any classes or associations that can be "liked" extend that module.
This lets you do things like...
If you needed to later, you could add methods to the module to see, eg, how many votes a particular Post has. You could also change the
post_id
to atarget_id
inVote
and make it a polymorphic association, and then you could use your Likable module to vote for anything, not just posts (you would need to generalize the call to find in most_liked if you did that).实际上,最好通过向 post 模型添加计数器缓存来完成,从而避免每次加载时都对数据库进行计数。
此railscast 剧集介绍了如何设置计数器缓存。
假设您将计数器缓存命名为 votes_count,您可以执行此操作以从控制器获取 10 个最受欢迎的帖子。
This is actually best done by adding a counter cache to the post model, avoiding the database count on every load.
This railscast episode explains how to setup the counter cache.
Assuming you named your counter cache votes_count, you can do this to get the 10 most popular posts from your controller.