首页 文章

喜欢/不喜欢Rails中的投票数据库

提问于
浏览
1

我正在以YouTube“喜欢”和“不喜欢”的方式为我们的网站创建投票功能,并使用Ruby on Rails 3为Digg创建投票功能 . 我无法提出正确的方案 .

我有三个模型,用户,主题和投票 . 每个用户将对一个主题进行一次“赞”或“不喜欢”投票 . 与这些网站一样,用户可以在主题上投票,但他们也可以创建新主题 . 我希望不仅能够查看所有用户的投票,还能查看他们创建的主题和他们投票的主题 . 我正在尝试自己构建它,并决定如何最好地设置数据库来处理此过程 .

我的第一个想法是使用:has_many和belongs_to完全如此...

class User <ActiveRecord :: Base

has_many:投票

has_many:主题

class Topic <ActiveRecord :: Base

has_many:投票

belongs_to:用户

class Vote <ActiveRecord :: Base

belongs_to:主题

belongs_to:用户

boolean choice #tracks用户选择Like还是Dislike

但很明显,这可能不是最好的方法 . 我开始认为最好的方法是使用a:has_many:通过关联...

class User <ActiveRecord :: Base

has_many:votes,:through =>:主题

但我不确定 . 关于如何最好地设置这样的东西的任何想法?

1 回答

  • 0

    我认为您的初始设置很好,但可以进一步改进以更好地支持您想要完成的任务 . 也许是这样的:

    class User < ActiveRecord::Base
      has_many :votes
      has_many :topics
    
      #Lists all topics the user has voted on
      has_many :voted_topics, :through => :votes, :source => :topic
    
      #Lists all votes for the users topics
      has_many :topic_votes, :through => :topics, :source => :votes
    end
    
    class Topic < ActiveRecord::Base
      has_many :votes
      belongs_to :user
    end
    
    class Vote < ActiveRecord::Base
      belongs_to :topic
      belongs_to :user
    end
    

相关问题