ruby-on-rails - rails 5 : How to pass attributes of a parent resource to a nested resource?

标签 ruby-on-rails

我有一个模型 MultipleChoiceQuestion,它有五个属性:answer_oneanswer_twoanswer_thirdanswer_fouranswer_ Five,以及名为 answer_ Correct

的字段

我想跟踪每个用户在加载每个问题后选择的onClick内容。可能使用 Remote: true - 我一直在互联网上阅读,似乎创建一个名为 UserAnswer 的嵌套多态模型将是一件明智的事情,以跟踪​​用户对每个问题的答案选择。

但是,我感到困惑的是如何将原始模型(MultipleChoiceQuestion)的参数传递给 View 中的新模型,因为我的理解是所有模型在数据库中都有不同的属性。 (当信息字符串来自父模型时,我如何确保可以保留用户通过单击辅助模型选择的内容?)

是否可以将父模型的属性传递给嵌套模型?这样做的目的是让用户随着时间的推移了解他们的正确或错误。

MultipleChoiceQuestion.rb 模型

# == Schema Information
#
# Table name: multiple_choice_questions
#
#  id                                         :bigint(8)        not null, primary key
#  question                                   :text
#  answer_one                                 :text
#  answer_two                                 :text
#  answer_three                               :text
#  answer_four                                :text
#  answer_correct                             :text
#  answer_explanation                         :text
#  published                                  :boolean
#  flagged                                    :boolean
#  user_id                                    :bigint(8)
#  created_at                                 :datetime         not null
#  updated_at                                 :datetime         not null
#  slug                                       :string           not null
#  source                                     :string
#  reviewed                                   :boolean
#  who_reviewed                               :string
#  reviewed_at                                :datetime
#  difficulty_rating                          :integer
#  multiple_choice_question_classification_id :integer
#  controversial                              :boolean          default(FALSE)
#  origination                                :integer          default("not_given")

Class MultipleChoiceQuestion < ApplicationRecord
  belongs_to :user, optional: true
  validates :user, presence: true

  belongs_to :multiple_choice_question_classification, optional: true

  has_many :flags, dependent: :destroy

  acts_as_taggable

  # activity feed
  include PublicActivity::Model
  tracked owner: Proc.new { |controller, model| controller.current_user ? controller.current_user : nil }

  validates :question, :slug, presence: true, length: { minimum: 5 }
  validates_uniqueness_of :question

User.rb模型

# == Schema Information
#
# Table name: users
#
#  id                     :bigint(8)        not null, primary key
#  email                  :string           default(""), not null
#  encrypted_password     :string           default(""), not null
#  reset_password_token   :string
#  reset_password_sent_at :datetime
#  remember_created_at    :datetime
#  sign_in_count          :integer          default(0), not null
#  current_sign_in_at     :datetime
#  last_sign_in_at        :datetime
#  current_sign_in_ip     :string
#  last_sign_in_ip        :string
#  created_at             :datetime         not null
#  updated_at             :datetime         not null
#  first_name             :string
#  last_name              :string
#  school_name            :string
#  graduation_year        :string
#  current_sign_in_token  :string
#  admin                  :boolean          default(FALSE)
#  superadmin             :boolean          default(FALSE)
#  verified               :boolean          default(FALSE)
#  premiumuser            :boolean          default(FALSE)
#  regularuser            :boolean          default(FALSE)
#  banneduser             :boolean          default(FALSE)
#  user_role              :boolean          default(TRUE)
#  username               :string           default(""), not null
class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :multiple_choice_questions, dependent: :destroy
  has_many :comments, dependent: :destroy

  has_many :flags
  has_many :saved_items

  has_one_attached :avatar

查看 - multiple_choice_questions/show.html.erb

<h5>
    <%= @multiple_choice_question.question %>
  </h5>

  <p>
    <span>Answer choice #1:</span>
    <%= @multiple_choice_question.answer_one %>
  </p>

  <p>
    <span>Answer choice #2:</span>
    <%= @multiple_choice_question.answer_two %>
  </p>

  <p>
    <span>Answer choice #3:</span>
    <%= @multiple_choice_question.answer_three %>
  </p>

  <p>
    <span>Answer choice #4:</span>
    <%= @multiple_choice_question.answer_four %>
  </p>

  <p class="correct">
    <span>Correct Answer:</span>
    <%= @multiple_choice_question.answer_correct %>
  </p>

最佳答案

如果您愿意保留当前的架构架构,那么您可能需要执行以下步骤来实现您的需求

步骤:(代码片段根据与OP的讨论进行更新)

1) 定义一个自定义路由,您可以在AJAX中使用它来发送用户选择的答案并接收结果。

#routes.rb
post '/verify_user_selected_answer', to: "multiple_choice_questions#verify_user_selected_answer'

2) 将答案作为链接供用户点击

<%= link_to @multiple_choice_question.answer_one, "javascript:void(0);", class: "answer" %>

3) 当用户点击答案时触发 AJAX 调用

$(document).ready(function() {
  $("a.answer").on( "click", function( event ) {
  var current_answer = $(this);
  var question_id = '<%= @multiple_choice_question.id %>';
  var current_user = "<%= current_user.id %>"; 

  $.ajax({
    url: "/verify_user_selected_answer",
    type: "POST",
    dataType: "json",
    data: {user_id: current_user, question: question_id, answer: current_answer.text()}, 
    success: function(response){
      $("#display_result").text(response["result"]); 
     }
  });
  });
});

4) 有一个div显示结果。

<div id="display_result">

5) 最后在 multiple_choice_questions#verify_user_selected_answer进行验证并返回结果

def verify_user_selected_answer
  @multiple_choice_question = MultipleChoiceQuestion.find(params[:question])
  @selected_answer = params[:answer]
  @user = User.find(params[:user_id])
  @multiple_choice_question.update_attribute(user_id, @user.id)

  if @selected_answer.downcase == @multiple_choice_question.answer_correct.downcase
    @result = "Correct answer!"
  else
    @result = "Wrong answer!"
  end

  respond_to do |format|
    format.json { render json: { result: @result } }
  end
end

关于ruby-on-rails - rails 5 : How to pass attributes of a parent resource to a nested resource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52817555/

相关文章:

mysql - 缺少 MySQL 客户端

ruby-on-rails - rails : How do I filter a ActiveRecord collection result without making new db queries?

javascript - 重复的 POST 方法,为什么?

ruby-on-rails - stub ActiveRecord 结果数组

ruby-on-rails - Ruby on rails - 参数数量错误(2 为 1)[Rails]

ruby-on-rails - 模型和表中是否都需要关联?

javascript - 使用Rails动态打印时无法访问html id标签

ruby-on-rails - 为什么 ruby​​ base64 与其他不同?

html - 为什么这个 formtastic CSS 不会在我的 Rails 3 应用程序中覆盖?

ruby-on-rails - 如何在 Rails 的链接中添加附加标签?