Rails 5-通过UJS /远程创建嵌套资源:是吗?

时间:2018-10-19 11:13:13

标签: ruby-on-rails

我有一个可行的实现,其中有一个名为MultipleChoiceQuestion的父资源,User可以拥有许多父资源。

MultipleChoiceQuestion具有几个属性,从question(本身就是问题)开始,连同其答案选择属性分别为answer_oneanswer_two,{{1} },answer_threeanswer_four以及answer_five

我需要能够显示问题以及所有答案选择,并允许用户选择答案,并将其保留下来,并让他们看到对或错的问题。

我在考虑必须创建一个新模型,例如answer_correct,但是考虑到它属于UserAnswer,我不确定它的属性是什么-以及如何将参数传递给这个新模型是我所坚持的。

以下是相关代码:

MultipleChoiceQuestions控制器

MultipleChoiceQuestion

tagged.html.erb

  def tagged
    @mcqs = MultipleChoiceQuestion.with_tag(params[:tag]).order("created_at DESC").paginate(:page => params[:page], :per_page => 1)
    authorize @mcqs
  end

def verify_user_selected_answer
    @multiple_choice_question = MultipleChoiceQuestion.find(params[:question])
    @selected_answer = params[:answer]
    @user_id_who_selceted = params[:current_user]


    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

routes.rb

  <% @mcqs.each do |mcq| %>
<% mcq.answers.each do |answer| %>
    <div class="gr-question--choice">
      <%= link_to answer, "javascript:void(0);", class: "answer" %>

    </div>

  <% end %>

<script>

$(document).ready(function() {
$("a.answer").on( "click", function( event ) {
var current_answer = $(this);
var question_id = '<%= mcq.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"]);
}
});
});
});

</script>

<% end %>

在rails控制台中,正在传递数据参数,这就是证明

  post '/verify_user_selected_answer', to: "multiple_choice_questions#verify_user_selected_answer"

它具有尝试输入的用户ID,问题ID和选择的答案。 我需要在一个单独的模型中坚持这些尝试,但是必须通过Ajax完成。

基本上,要查看有多少人尝试了单个问题,由谁选择了哪个选项,以及用户自己应该能够看到随着时间的推移对与错的问题?帮助-谢谢!

编辑:

MultipleChoiceQuestion.rb

Started POST "/verify_user_selected_answer" for 127.0.0.1 at 2018-10-19 16:15:16 +0500
Processing by MultipleChoiceQuestionsController#verify_user_selected_answer as JSON
  Parameters: {"user_id"=>"1", "question"=>"77", "answer"=>"answer four"}

User.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


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 }

  extend FriendlyId
  friendly_id :question, use: %i(slugged history finders)

  def should_generate_new_friendly_id? #will change the slug if the name changed
    question_changed?
  end

  def answers
    [answer_one, answer_two,
    answer_three, answer_four,
    answer_correct].shuffle
  end


end

1 个答案:

答案 0 :(得分:1)

您的问题可以通过经典的has_many, <> :through关联来解决。步骤应包括以下内容

步骤:

1)使用以下命令生成一个新模型,例如UserAnswer

rails g generate model UserAnswer user_id:integer multiple_choice_question_id:integer selected_answer:text is_correct_answer:boolean

并执行rake db:migrate将表添加到数据库中。

2)删除user_id表中的multiple_choice_questions列。您现在不需要它了

3)更改关联以包括新模型

#multiple_choice_question.rb
has_many :user_answers
has_many :users, through: :user_answers

#user.rb
has_many :user_answers
has_many :multiple_choice_questions, through: :user_answers

#user_answer.rb
belongs_to :user
belongs_to :multiple_choice_question

4)在user_answers方法中为verify_user_selected_answer添加条目的创建,如下所示

def verify_user_selected_answer
  @multiple_choice_question = MultipleChoiceQuestion.find(params[:question])
  @selected_answer = params[:answer]
  @user_id_who_selceted = User.find(params[:user_id]) #look for the change here

  if @selected_answer.downcase == @multiple_choice_question.answer_correct.downcase
    UserAnswer.create(multiple_choice_question_id: @multiple_choice_question.id, user_id: @user_id_who_selceted.id, selected_answer: @selected_answer, is_correct_answer: true)
    @result = "Correct answer!"
  else
    UserAnswer.create(multiple_choice_question_id: @multiple_choice_question.id, user_id: @user_id_who_selceted.id, selected_answer: @selected_answer, is_correct_answer: false)
    @result = "Wrong answer!"
  end

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

这将使您每次用户选择问题答案时都可以向user_answers添加新条目。