Model association question

2019-02-20 16:01发布

So I'm implementing an up/down voting mechanism for which I'm generating a model. So far I understand that a video (what will be voted on) has one vote_count, and vote_count belongs to videos. However, I also want to track in my vote_count database the user that has voted on the video. Does that mean that a vote_count has many users, and that a user belongs to a vote_count?

2条回答
太酷不给撩
2楼-- · 2019-02-20 16:14

Am I missing something here? Why not assign a netVoteTally as a property of Videos. Initialize it to zero when video.new is called and have incNetVideoTally and decNetVideoTally methods that are accessible outside the video method? Just my $0.02.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-20 16:35

It may be easier to track the votes as independent records, such as this:

class VideoVote < ActiveRecord::Base
  belongs_to :user
  belongs_to :video
end

class User < ActiveRecord::Base
  has_many :video_votes
  has_many :voted_videos,
    :through => :video_votes,
    :source => :video
end

class Video < ActiveRecord::Base
  has_many :video_votes,
    :counter_cache => true
  has_many :voted_users,
    :through => :video_votes,
    :source => :user
end

If you have people voting up and down, you will need to track the net vote total somehow. This can be tricky, so you may want to look for a voting plugin.

查看更多
登录 后发表回答