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

折月煮酒 提交于 2019-12-02 10:26:21

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!