Rails4: Formtastic3.0 , save multiple instances (for Answer models) at the same time

后端 未结 1 2029
囚心锁ツ
囚心锁ツ 2021-01-28 21:07

I have Question model and an answer model.

Each question can have one answer per user. I am trying to preset to a user a form to answer all questions, but couldnt reall

相关标签:
1条回答
  • 2021-01-28 21:40

    Rather then making a form for @questions you need to pass a single object to your form helper (@questions is an array of questions). A good way to achieve this is though a form object.

    # app/forms/questions_form.rb
    class QuestionsForm
      include ActiveModel::Model
    
      def initialize(user)
        @user = user
      end
    
      def questions
        @questions ||= Question.all
      end
    
      def submit(params)
        params.questions.each_pair do |question_id, answer|
          answer = Answer.find_or_initialize_by(question_id: question_id, user: current_user)
          answer.content = answer
          answer.save
        end
      end
    
      def answer_for(question)
        answer = answers.select { |answer| answer.question_id == question.id }
        answer.try(:content)
      end
    
      def answers
        @answers ||= @user.answers.where(question: questions)
      end
    end
    

    Then in your controller you'd have:

    # app/controllers/submissions_controller.rb
    Class SubmissionsController < ApplicationController
      ...
      def new
        @questions_form = QuestionsForm.new(current_user)
      end
    
      def create
        @questions_form = QuestionsForm.new(current_user)
    
        @questions_form.submit(params[:questions_form])
        redirect_to # where-ever
      end
      ...
    end
    

    In your view you'll want something along the lines of:

    # app/views/submissions/new.html.haml
    = form_for @questions_form, url: submissions_path do |f|
      - @questions_form.questions.each do |question|
        %p= question.content
        = f.text_field "questions[#{question.id}]", value: @questions_form.answer_for(question)
      = f.submit "Submit"
    

    This doesn't use formtastic at all, it's just using the plain rails form helpers.

    This code isn't tested so not sure if it even works but hopefully it helps get you on the right track.

    0 讨论(0)
提交回复
热议问题