我是Rails 3.2上的Ruby 1.9.3的新手,并致力于个人项目的学习。这是一个非常基本的多选琐事游戏,我在控制器和视图中编写代码时遇到麻烦,使用户能够点击随机显示问题和question_choices的“播放”链接。然后,用户应该选择对应于四个问题选择之一的四个单选按钮中的一个。问题和question_choice被添加到user_answers表中,然后显示下一个问题。另外,我不希望用户两次看到相同的问题。
以下是我的模特:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_many :questions
has_many :question_choices
has_many :user_answers, dependent: :destroy
end
class Question < ActiveRecord::Base
attr_accessible :level, :question, :is_active
has_many :user_answers, through: :question_choices
has_many :question_choices, dependent: :destroy
end
class QuestionChoice < ActiveRecord::Base
attr_accessible :choice, :is_correct, :question_id
has_many :user_answers, dependent: :destroy
belongs_to :question
end
class UserAnswer < ActiveRecord::Base
attr_accessible :answer_time, :user_id, :question_choice_id, :question_id
belongs_to :user
belongs_to :question
belongs_to :question_choice
end
我的路线:
Trivia::Application.routes.draw do
root to: 'static_pages#home'
resources :sessions, only: [:new, :create, :destroy]
resources :questions do
resources :question_choices
end
resources :users
resources :user_answers
end
我已经能够将脚手架用于'index','new','edit'&amp;每个人分别“显示”,但是我很难将它们捆绑在一起,因此用户可以看到一个问题和问题选择,然后选择一个,他们的UserAnswers会更新。
非常感谢任何帮助。
谢谢。 沙恩
答案 0 :(得分:2)
我认为您的数据模型有点复杂。我们来看看要求
我们有三个对象:用户,问题和答案(QuestionChoices)。 我们知道这些对象之间关系的一些事情:
1号是一个简单的关系,问题有很多问题选择:
class Question < ActiveRecord::Base
attr_accessible :level, :question, :is_active
has_many :question_choices, dependent: :destroy
end
Number 2与用户模型有关,这非常简单:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_many :user_answers, :dependent => :destroy
end
好的,现在是UserAnswers。它的工作是将问题选择与用户联系起来:
class UserAnswer < ActiveRecord::Base
attr_accessible :answer_time, :user_id, :question_choice_id, question_id
belongs_to :user
belongs_to :question
belongs_to :question_choice
validates :question_id, uniqueness: { :scope => :user_id }
end
该验证是第4号的答案。它说“如果根据用户将所有用户答案组合在一起,则每个问题只应出现一次。”因此,如果用户尝试回答两次问题,它将拒绝在数据库中创建此项目。
第三个并不是真正的要求,但您需要确保数据模型的控制权。我们没有什么可以阻止这种情况。