Rails 5: Как передать атрибуты родительского ресурса во вложенный ресурс? - PullRequest
0 голосов
/ 15 октября 2018

У меня есть модель, MultipleChoiceQuestion, которая имеет пять атрибутов: answer_one, answer_two, answer_three, answer_four и answer_five вместе с полем с именем answer_correct

Я хочу отслеживать, что каждый пользователь выбирает onClick после загрузки каждого вопроса.Вероятно, с помощью remote: true - я читал в Интернете, и кажется, что было бы разумно создать вложенную полиморфную модель с именем UserAnswer, чтобы отслеживать выбор ответа пользователя на вопрос.

Однако меня смущает то, как я передам параметры исходной модели (MultipleChoiceQuestion) новой модели в представлении, так как я понимаю, что все модели имеют разные атрибуты в базе данных.(Как мне убедиться, что я могу сохранить то, что пользователь выбрал своим кликом через вторичную модель, когда информационные строки поступают из родительской модели?)

Можно ли передать атрибуты родительской модели во вложенную модель?один?Цель здесь - дать пользователям возможность увидеть, что они поняли правильно или неправильно со временем.

Модель 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

Представление - множественные_четы_данных / 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>

Ответы [ 2 ]

0 голосов
/ 18 октября 2018

Если вы хотите остаться с вашей текущей архитектурой схемы, то вам может потребоваться следующие шаги для достижения того, что вам нужно

Шаги: (фрагменты кода обновляются согласно обсуждениюс помощью 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
0 голосов
/ 17 октября 2018

Вот что я хотел бы сделать:

Во-первых, вам нужно иметь какую-то ссылку на ваш экзамен или тест.Во-вторых, ваш экзамен должен иметь х количество вопросов.В-третьих, у вас должно быть x возможных ответов с одним правильным.Затем вы берете свою модель пользователя и связываете этого пользователя с тестами и ответами, подобными этим.

Обратите внимание, что это недопустимый синтаксис, но только для пояснения.

class Exam has_many :questions
           has_and_belongs_to_many :users

class Question has_many :answers
               has_many :user_answers
               belongs_to :exam

class Answer belongs_to :question

class UserAnswer belongs_to :question
                 belongs_to :user

class User has_and_belongs_to_many :exams
           has_many :user_answes

Теперь вы можете связать любой экзамен с любым пользователем, а также связать любой ответ с любым пользователем.

Так, например, если вы отправите форму своему контроллеру Answers, вы можетезатем создайте ассоциации, которые бы отслеживали ранее выбранные ответы для каждого пользователя следующим образом:

            answer = Answer.find(params[:id])
            user_answer = UserAnswer.create(answer_id: answer.id, user_id: user.id, question_id: answer.question.id)

Так что теперь вы можете сделать довольно соединения с вашими моделями User, Exam и UserAnswer, чтобы получитькаждый ответ пользователя на конкретный экзамен.Если вы используете свою текущую структуру модели, вы можете получить ее, но она не будет настолько масштабируемой, и вам, вероятно, придется взломать ее, чтобы заставить ее работать так, как вы хотите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...