1

我正在使用 Ruby on Rails 3 为我们的网站以 YouTube“喜欢”和“不喜欢”和 Digg 的风格创建投票功能。我在想出正确的方案时遇到了麻烦。

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

我的第一个想法是像这样专门使用 :has_many 和 belongs_to……</p>

类用户 < ActiveRecord::Base

has_many:投票

has_many:主题

类主题 < ActiveRecord::Base

has_many:投票

属于_to:用户

类投票 < ActiveRecord::Base

属于_to:主题

属于_to:用户

布尔选择 #tracks 用户是否选择喜欢或不喜欢

但很明显,这可能不是最好的方法。我开始认为最好的方法是使用 :has_many :through 关联,例如...

类用户 < ActiveRecord::Base

has_many :votes, :through => :topics

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

4

1 回答 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
于 2010-12-16T03:19:31.143 回答