我有一些参加测验的用户。我跟踪他们选择的结果。我需要弄清楚如何让他们更改他们的测验提交。如果我只是将答案联系起来,他们会回答两次这个问题。建立数据很复杂,ActiveRecord 是否提供了一种方法来处理这个问题?
整个示例将在独立文件中运行。
这是我的架构:
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
self.verbose = false
create_table :users do |t|
t.string :name
end
create_table :questions do |t|
t.string :name
end
create_table :question_results do |t|
t.string :name
t.integer :question_id
end
create_table :question_results_users do |t|
t.integer :user_id
t.integer :question_result_id
end
end
这是我的模型:
class User < ActiveRecord::Base
has_and_belongs_to_many :question_results
has_many :questions, through: :question_results
end
class Question < ActiveRecord::Base
has_many :question_results
end
class QuestionResult < ActiveRecord::Base
belongs_to :question
has_and_belongs_to_many :users
end
让我们提出三个问题和一些答案:
Question.create! name: "What's your favourite movie?" do |question|
question.question_results.build name: 'Gattaca'
question.question_results.build name: 'Super Troopers'
end
Question.create! name: 'Who do you want to be president?' do |question|
question.question_results.build name: 'Barack Obama'
question.question_results.build name: 'Mitt Romney'
question.question_results.build name: 'Mickey Mouse'
end
Question.create! name: "What's your favourite colour?" do |question|
question.question_results.build name: 'black'
question.question_results.build name: 'green'
end
让我们创建一个用户:
jim = User.create! name: 'Jim'
jim.question_results << QuestionResult.find_by_name('Gattaca')
jim.question_results << QuestionResult.find_by_name('Barack Obama')
jim.question_results << QuestionResult.find_by_name('black')
jim.question_results # => [#<QuestionResult id: 1, name: "Gattaca", question_id: 1>, #<QuestionResult id: 3, name: "Barack Obama", question_id: 2>, #<QuestionResult id: 6, name: "black", question_id: 3>]
jim.question_results.map(&:question) # => [#<Question id: 1, name: "What's your favourite movie?">, #<Question id: 2, name: "Who do you want to be president?">, #<Question id: 3, name: "What's your favourite colour?">]
现在 Jim 改变了主意,他决定喜欢 Super Troopers 并且不想投票,但他仍然喜欢黑色。我如何在不让他多次回答问题的情况下更新它?
# pretend we're in a controller here (also note that I can change the format of the data, if there is something more convenient)
posted_from_form = {
questions: {
Question.all[0].id => 'Super Troopers',
Question.all[1].id => '',
Question.all[2].id => 'black',
}
}