Rails4:Formtastic3.0,同时保存多个实例(对于答案模型)

时间:2014-10-20 00:24:20

标签: html forms ruby-on-rails-4 simple-form formtastic

我有问题模型和答案模型。

每个问题每个用户可以有一个答案。我正在尝试向用户预设一个表单以回答所有问题,但无法真正弄清楚如何使用formtastic进行此操作

这是我到目前为止所拥有的

    - @questions.each do |q|
      = q.content
      - ans = @user.answers.where(question_id:q.id).first.try(:content) || q.description
      = semantic_form_for @answers do |f|
        = f.label q.content
        = f.inputs :content, placeholder: ans 
      = f.actions

我正试图从How to loop through two alternating resources on a form?获得一些提示但是如果我尝试的话,我会继续为@questions获取“未定义的方法`model_name'for Class:Class”:

= semantic_form_for @questions do |q|
  = q.input :content
  = q.semantic_fields_for @answer do |a|
    = a.inputs :content
  = q.actions

基于Railscast 198, but using formtastic这是我的尝试不起作用:

- semantic_form_for :Answer, :url => api_v1_answers_path, :method => :put do |f|
  - @questions.each do |q|
    - f.fields_for 'questions[]', q do |ff|
      = q.content
      = ff.input
  = submit_tag "Submit"

注意:

1]我希望用户在添加/编辑所有答案后只提交一次

2]如果已经存在答案,则应在文本框中预先填写

3]如果能让生活更轻松,我不介意使用simple_form gem

1 个答案:

答案 0 :(得分:0)

而不是为@questions制作表单,您需要将单个对象传递给表单助手(@questions是一系列问题)。实现这一目标的一个好方法是使用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

然后在你的控制器中你有:

# 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

在您看来,您会想要以下内容:

# 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"

这根本不使用formtastic,它只是使用普通的rails帮助者。

此代码未经过测试,因此不确定它是否有效,但希望它能帮助您走上正确的道路。