이 작업을 수행하는 방법은 여러 가지가 있지만 아마도 가장 다양하고 레일 틱은 순위를 할 수있는 방법으로 모듈을 만들 수 다음 "좋아 할 수있는 클래스 나 연관됩니다 "그 모듈을 확장하십시오.
# 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.most_liked # => an array of the 10 most liked posts
@some_user.posts.most_liked(5) # => that user's 5 most liked posts
은 나중에, 특정 포스트 얼마나 많은 표를, 예를 볼 수있는 모듈에 메소드를 추가 할 수 필요합니다. post_id
을 Vote
에 으로 변경하고 다형성 연관성을 부여한 다음 Likable 모듈을 사용하여 게시물뿐만 아니라 무엇이든 투표 할 수 있습니다 (전화를 일반화해야 most_liked에서 찾게됩니다.).
득표표에 투표 당 1 개의 기록이 있거나 총 투표 수와 함께 게시물 당 하나의 기록이 있습니까? – mikej