2012-09-23 2 views
0

사용자가 게시 할 수있는 앱이 있습니다. 각 게시물을 upvoted 및 downvoted 수 있습니다. 각 사용자는 또한 자신의 게시물에서 upvotes 및 downvotes에서 계산 된 평판을 가지고 있습니다. 이제, 나는 두 곳에서 각 포스트의 upvotes와 downvotes를 추적합니다. 첫째, 내 게시물 테이블이 : 나는 또한 사용자가 (0 투표는 투표권없는 이미 게시물에 투표 한 내가 알고있는 있도록 별도의 '투표'테이블과 각 투표를 추적게시물에 대해 투표와 투표를 모델로 만드는 방법은 무엇입니까?

create_table "posts", :force => true do |t| 
    t.integer "user_id" 
    t.text  "content" 
    t.integer "upvotes", :default => 0 
    t.integer "downvotes", :default => 0 
    t.datetime "created_at",    :null => false 
    t.datetime "updated_at",    :null => false 
    end 

, 내가 원래 두 개의 서로 다른 테이블에 포스트 투표의 트랙을 유지

create_table "votes", :force => true do |t| 
    t.integer "user_id" 
    t.integer "post_id" 
    t.integer "vote",  :default => 0 
    t.datetime "created_at",    :null => false 
    t.datetime "updated_at",    :null => false 
    end 

특정 포스트 투표 수를 조회하는 것이보다 효율적으로하기 : 1의 투표가 downvote이며, 2의 투표는 upvote에)입니다 예를 들어 다음과 같습니다.

post_reputation = post.upvotes - post.downvotes 

그러나 나는 이것이 나쁜 관행이며 투표 데이터가 중복되지 않도록 내 '게시물'테이블에서 'upvotes'및 'downvotes'열을 삭제해야한다고 생각합니다.

def calculate_post_reputation(post_id) 
    some_post = Post.find(post_id) 
    vote_count = 0 
    some_post.votes.each do |vote| 
    if vote.vote.to_i == 2 
     vote_count += 1 
    elsif vote.vote.to_i == 1 
     vote_count -= 1 
    end 
    end 
    vote_count 
end 

이 포스트 명성을 계산하기 위해 'upvotes'와 'downvotes'열을 유지하거나 삭제하고 '투표'테이블을 사용하는 것이 좋습니다 : 나는 다음과 같은 일을하고 사후 명성을 계산합니다?

Models: 

class User < ActiveRecord::Base 
    has_many :votes 
    has_many :posts, :through => votes 

class Post < ActiveRecord::Base 
    has_many :votes 
    has_many :users, :though => :votes 

class Vote < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :post 
    attr_accessor :direction 
    UP='Up' 
    DOWN='Down' 
    DIRECTIONS=[UP,DOWN] 
    validates_inclusion_of :direction, in: [DIRECTIONS] 
    scope :up_votes where(:direction => UP) 
    scope :down_votes where(:direction => DOWN) 

그런 다음 위 또는 표 아래의 번호를 Post.votes.up_votes.countPost.votes.down_votes.count를 사용

답변

0

나는 (의사 코드) 고려할 것입니다.

약술 한 접근법은 SQL에서 다루는 방법입니다. 위의 내용은 레일스 스타일의 접근 방식입니다. 적절한 db 마이그레이션을 추가해야합니다.

관련 문제