【发布时间】:2018-02-25 00:33:30
【问题描述】:
我正在构建一个创建考试的应用程序。对于用户在考试中选择答案的部分,我想使用一个复选框(或单选按钮)让他们选择答案。
我希望所有用户选择的答案都是一个名为“响应”的表格。我不知道如何使用单选按钮来创建记录。
所有响应记录需要做的就是获取考试、用户和分数的 ID。分数是一个表格,用于跟踪用户的分数和正确答案的数量。 这是我的考试模型(rails 不允许我使用“考试”这个词)。我已经为嵌套属性设置了它。
class Examination < ApplicationRecord
belongs_to :user
has_many :questions, dependent: :destroy
has_many :scores
has_many :responses
has_secure_password
accepts_nested_attributes_for :responses, allow_destroy: true
end
响应模型非常基本:
class Response < ApplicationRecord
belongs_to :user
belongs_to :score
belongs_to :examination
end
这是“参加考试”页面:
<h2><%= @exam.name %></h2>
<h3><%= @exam.intro %></h3>
<%= form_for @exam do |f| %>
<%= f.hidden_field :name, value: @exam.name %>
<%= fields_for :responses do |res_f| %>
<% @exam.questions.each_with_index do |question, i| %>
<% index = i + 1 %>
<h2>Question #<%=index%></h2><span style="font-size: 24px; font-weight: normal">(<%= question.points %> Points)</span>
<hr>
<h3><%= question.body %></h3>
<% question.answers.each do |ans| %>
<table>
<tr>
<td><%= res_f.check_box :answer_id , ans.id, :examination_id , @exam.id, :user_id %></td>
<td><%= ans.body %></td>
</tr>
</table>
<% end %>
<% end %>
<% end %>
<%= f.submit 'Submit' %>
<% end %>
此代码不会运行,因为 Rails 期望响应记录存在才能使用表单。它抛出这个错误:
undefined method `merge' for 484:Integer
如果我将该复选框代码调整为:
<%= res_f.check_box :answer_id %>
代码将运行,它会在提交时为我提供以下参数:
Started PATCH "/examinations/34" for 127.0.0.1 at 2018-02-24 16:22:41 -0800
Processing by ExaminationsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"y4vcPByUKnDdM6NsWDhwxh8MxJLZU4TQo+/fUrmKYEfb3qLn5FVieJAYirNRaSl0w5hJax20w5Ycs/wz1bMEKw==", "examination"=>{"name"=>"Samuel Smith’s Oatmeal Stout"}, "responses"=>{"answer_id"=>"1"}, "commit"=>"Submit", "id"=>"34"}
我知道这不对,但我希望它至少会创造一个记录。所有复选框都必须创建响应记录。它应该能够获取 answer_id、exam_id 和 user_id。就是这样。
有人知道怎么做吗?
编辑以回应巴勃罗 7: 这是其他模型(它们现在非常基本)
class Score < ApplicationRecord
belongs_to :user
belongs_to :examination
has_many :responses, dependent: :destroy
end
class User < ApplicationRecord
has_many :examinations, dependent: :destroy
has_many :scores, dependent: :destroy
has_many :responses, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class Question < ApplicationRecord
belongs_to :examination
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers, allow_destroy: true
validates_presence_of :body
validates_presence_of :question_type
end
@exam 和 Exam 是一样的。考试控制器中有一个“采取”操作,允许用户参加考试:
def take
@exam = Examination.find(params[:id])
@score = @exam.scores.build
@score.user_id = current_user.id
@score.save
end
所以考试属于创建它的用户。同一用户或不同用户可以使用采取行动参加考试。然后他们就会有一个属于他们的分数。
【问题讨论】:
-
你能添加你的问题、分数和用户模型吗?考试和考试是一样的吗?如果是,是否真的和检查属于_一个用户? (没有其他用户参加相同的考试)?
-
嗨,Pablo,我在问题中添加了更多细节。希望这会有所帮助。真正的问题是如何使用复选框来创建“响应”记录。
标签: ruby-on-rails checkbox nested-forms nested-attributes