Ruby on rails 按“数量”显示帖子;投票“;单独表格中的记录
我对Rails还不熟悉,所以请放心。我创建了一个博客,还为用户提供了显示他们“喜欢”某篇文章的功能。我实现这一点的方式是使用post表和单独的表“投票”。当用户单击“like”按钮时,它会将记录发送到“vote”表,其值为“1”,并带有特定的post id 我想在侧边栏中显示“最喜欢”的帖子。我该怎么称呼这样的事呢。我想显示帖子标题和“投票数”,也就是说,我想以某种方式查询“投票”表中记录最多的帖子id,并按降序显示它们Ruby on rails 按“数量”显示帖子;投票“;单独表格中的记录,ruby-on-rails,ruby,blogs,Ruby On Rails,Ruby,Blogs,我对Rails还不熟悉,所以请放心。我创建了一个博客,还为用户提供了显示他们“喜欢”某篇文章的功能。我实现这一点的方式是使用post表和单独的表“投票”。当用户单击“like”按钮时,它会将记录发送到“vote”表,其值为“1”,并带有特定的post id 我想在侧边栏中显示“最喜欢”的帖子。我该怎么称呼这样的事呢。我想显示帖子标题和“投票数”,也就是说,我想以某种方式查询“投票”表中记录最多的帖子id,并按降序显示它们 我希望这是一个简单的问题 这实际上最好通过向post模型添加计数器缓存来实
我希望这是一个简单的问题 这实际上最好通过向post模型添加计数器缓存来实现,避免每次加载时的数据库计数 这说明了如何设置计数器缓存 假设您将计数器缓存票数命名为\u count,您可以这样做,从控制器中获取10条最受欢迎的帖子
@popular_posts = Post.find(:all, :limit => 10, :order => "votes_count DESC")
这实际上最好通过向post模型添加计数器缓存来实现,避免每次加载时的数据库计数 这说明了如何设置计数器缓存 假设您将计数器缓存票数命名为\u count,您可以这样做,从控制器中获取10条最受欢迎的帖子
@popular_posts = Post.find(:all, :limit => 10, :order => "votes_count DESC")
有几种方法可以实现这一点,但最通用和最简单的方法可能是使用一种方法创建一个模块来进行排名,然后让任何可以“喜欢”的类或关联扩展该模块
# lib/likable.rb
#
module Likable
def most_liked (limit = 10)
# This may be possible without a find_by_sql... see the API docs.
find_by_sql("SELECT Posts.*, SUM(votes.count) AS num_votes FROM Posts, Votes WHERE Posts.id = post_id GROUP BY post_id ORDER BY num_votes DESC LIMIT #{limit}")
end
end
# app/models/post.rb
#
require 'likable'
class Post < ActiveRecord::Base
extend Likable
# ...whatever else you've got in here
end
# app/models/user.rb (or any other model with things that can be "liked")
#
require 'likable'
class User < ActiveRecord::Base
has_many :posts, :extend => Likable
# ...the rest of the User class
end
如果以后需要,可以向模块中添加方法,以查看特定帖子的投票数。您还可以在投票中将
post\u id
更改为target\u id
,并使其成为多态关联,然后您可以使用您的Likable模块为任何内容投票,而不仅仅是帖子(如果您这样做,您需要概括调用以查找最喜欢的内容)。有几种方法可以实现这一点,但最通用和最简单的方法可能是创建一个模块,使用一个方法进行排名,然后让任何可以“喜欢”的类或关联扩展该模块
# lib/likable.rb
#
module Likable
def most_liked (limit = 10)
# This may be possible without a find_by_sql... see the API docs.
find_by_sql("SELECT Posts.*, SUM(votes.count) AS num_votes FROM Posts, Votes WHERE Posts.id = post_id GROUP BY post_id ORDER BY num_votes DESC LIMIT #{limit}")
end
end
# app/models/post.rb
#
require 'likable'
class Post < ActiveRecord::Base
extend Likable
# ...whatever else you've got in here
end
# app/models/user.rb (or any other model with things that can be "liked")
#
require 'likable'
class User < ActiveRecord::Base
has_many :posts, :extend => Likable
# ...the rest of the User class
end
如果以后需要,可以向模块中添加方法,以查看特定帖子的投票数。您还可以在
Vote
中将post\u id
更改为target\u id
,并使其成为多态关联,然后您可以使用您的Likable模块为任何内容投票,而不仅仅是posts(如果您这样做,您需要概括调用以查找最喜欢的内容).您在投票表中每一票有一条记录,还是每帖子有一条记录,记录总票数?您在投票表中每一票有一条记录,还是每帖子有一条记录,记录总票数?