访问嵌套表单数据

时间:2017-10-09 00:10:56

标签: ruby-on-rails ruby postgresql simple-form

我正在尝试为在线单页测验构建一个应用程序,所以我使用的是嵌套表单。当我尝试从嵌套类访问数据时出现问题,我对如何将其作为最佳实践进行处理感到困惑。

该应用程序有一个Quiz类,它有问题,每个问题都有多个替代品。

quizzes_controller.rb:

def take
    @quiz = Quiz.find(params[:id])
    @user_quiz = @quiz
    #SAVE ANSWERS TO CURRENT USER
end

<小时/> take.html.erb:

<%= simple_form_for @user_quiz do |quiz| %>
    <%= quiz.simple_fields_for :questions do |question| %>
    **<!-- this should show question.statement -->**
        <div class="custom-controls-stacked">
            <%= question.input :answer, collection: **#this should be question.alternatives**
            ,as: :radio_buttons, class:"custom-control-input" %>
        </div>
    <% end %>

<%= quiz.button :submit %>
<% end %>

<小时/> quiz.rb:

class Quiz < ApplicationRecord
  belongs_to :session
  has_many :questions
  accepts_nested_attributes_for :questions
end

<小时/> question.rb

class Question < ApplicationRecord
  belongs_to :quiz
  has_many :alternatives
end

alternative.rb

class Alternative < ApplicationRecord
    belongs_to :question
end

<小时/> schema.rb

ActiveRecord::Schema.define(version: 20171008213618) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "alternatives", force: :cascade do |t|
    t.text "answer"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "question_id"
    t.index ["question_id"], name: "index_alternatives_on_question_id"
  end


  create_table "questions", force: :cascade do |t|
    t.text "statement"
    t.integer "correct_answer"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "quiz_id"
    t.integer "answer", default: 0
    t.index ["quiz_id"], name: "index_questions_on_quiz_id"
  end

  create_table "quizzes", force: :cascade do |t|
    t.integer "minutes", default: 20
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "session_id"
    t.index ["session_id"], name: "index_quizzes_on_session_id"
  end


end

当问题是嵌套类时,如何访问所述数据(question.statement是一个字符串,问题是has_many替代品)?

0 个答案:

没有答案