0

我想知道在我花费大量时间重写我的代码可能无济于事之前,您是否可以给我一些关于如何使用 has_many :through 关联的建议。

我有一个用户模型,每个用户可以玩很多测验(因此会产生很多测验分数)。现在,玩家通过单击用户名开始游戏,这会触发对该用户(用户 has_many :questions)所做的所有测验问题的查询

  def startGame 

     user = User.find_by_name(params[:user])
     questions = user.questions

  end 

由于显而易见的原因,一个玩家不能两次玩同一个测验。尽管我想出了一种方法来防止这种情况发生,但我并没有采取有效的方法。有人建议我尝试关联表。has_many :through我用这个计划开始了那个关联表

User.rb(此用户是用户作为玩家,而不是用户作为测验制作者)

has_many :scores
has_many :quizzes, :through => :scores

测验.rb

   has_many :scores
   has_many :users    :through => :scores

分数

   belongs_to :user
   belongs_to :quiz

问题是,目前没有测验模型或测验任何东西。测验实际上只是由问题 (Question.rb) 和答案 (Answer.rb) 组成。例如,每个用户has_many :questions和每个问题都has_many :answers像这样

用户.rb

has_many :questions

问题.rb

has_many :answers

那么我可以用什么来制作 Quiz 模型(或任何我称之为的模型)?

我想到的一个想法是制作一个 Quiz.rb 模型并做

has_many :questions

这意味着 Question.rb 属于 User.rb 和 Quiz.rb。

然后我可以对has_many :through用户、测验和分数进行上述操作吗?如果是这样,Score 将有一个 user_id(用于玩家)和一个 quiz_id(用于测验),但由于整个关联的目的是防止用户两次玩同一个测验,我想知道如何才能做到使用以下代码。

  def startGame

   user = User.find_by_name(params[:user])  #this user is the quiz creator
   questions = user.questions
     .....
    #I want to check right here if they've already played the quiz. how to do it with the has_many :through of Quiz, Score, User (as player)

  end

设置了 user.rb(玩家)、score.rb、quiz.rb 后,我将如何检查他们在这种情况下是否玩过这个特定的测验。

另外,如果我制作测验模型并做 has_many :questions,我是否必须使用多态性,因为 user.rb 也有 has_many :questions?

更新:我想检查他们是否已经在该def startGame方法中玩过,如果有的话,不要让他们继续游戏。即,我不想等到保存分数的时候才查看该测验的分数是否已经保存。

4

1 回答 1

2

你的代码看起来已经很好了。如果您想阻止任何玩家多次进行测验,您可以将用户和测验的任意组合设为唯一。您可以将此添加到您的分数迁移中:

add_index :scores, [:user_id, :quiz_id], unique: true

并将其添加到您的分数模型中:

validates_uniqueness_of :user_id, scope: quiz_id
于 2013-03-15T04:47:16.153 回答