【问题标题】:How to create multiple fields of the table column, submitted for a form如何创建表格列的多个字段,为一个表单提交
【发布时间】:2014-01-15 07:52:56
【问题描述】:

我不知道这个问题的正确标题是什么,抱歉。

我有一个Question 模型,用户应该输入让我们说 5 个问题,然后将它们提交到问题表。

问题是它只提交一个问题,即最后一个问题。

如何让它同时提交所有问题字段?

观看次数:

<% question_numbering = 0 %>

<%= simple_form_for(@quiz, html: {class: 'form-vertical' }) do |f| %>
    <%= render 'shared/error_messages_question' %>

    <div>
        <%=  %>
        question <%= question_numbering += 1 %><br>
        <%= f.input_field :content, :rows => 3, :style => "width:80%", :placeholder => "enter your question."  %><br>
        question <%= question_numbering += 1 %><br>
        <%= f.input_field :content, :rows => 3, :style => "width:80%", :placeholder => "enter your question."  %><br>
        question <%= question_numbering += 1 %><br>
        <%= f.input_field :content, :rows => 3, :style => "width:80%", :placeholder => "enter your question."  %><br>
        question <%= question_numbering += 1 %><br>
        <%= f.input_field :content, :rows => 3, :style => "width:80%", :placeholder => "enter your question."  %><br>
        question <%= question_numbering += 1 %><br>
        <%= f.input_field :content, :rows => 3, :style => "width:80%", :placeholder => "enter your question."  %><br>
    </div>
    <%= f.submit 'Submit', :class => "btn btn-default" %>
<% end %>

控制器:

class QuestionsController < ApplicationController
  def index
    @quiz = Question.new
    @questioner = Questioner.new
  end

  def new
    @quiz = Question.new(quiz_params)
  end

  def show
    @quiz = Question.find(params[:id])
  end

  def edit
    @quiz = find(params[:id])
    raise "Question Not edited!" unless @quiz
  end

  def create
    @quiz = Question.new(quiz_params)

    if @quiz.save
      flash[:warning] = 'You have successfully posted the questions!'
      redirect_to questions_path
    else
      flash[:error] = "Please review the problems below."
      # render 'new'
      redirect_to questions_path
    end
  end

  private

    def quiz_params
      params.require(:question).permit(:content, :answered, :questioner_id, :category_id)
    end
end

【问题讨论】:

    标签: ruby-on-rails ruby forms ruby-on-rails-4


    【解决方案1】:

    您目前正在使用问题资源 - 一次创建一个问题才真正有意义,因为它们不作为一个集合存在,而是作为单独的单元存在。

    如果您有另一个资源,例如 Quiz,它有很多问题 - 那么一次创建多个问题是有意义的。

    您需要将测验创建为单独的资源,并具有与问题关联的has_many

    查看this great Railscast on nested forms,它应该可以帮助您解决这个问题(这是我开始学习 Rails 的地方)。

    【讨论】:

    • @thanks man,这似乎很有帮助。我一直在寻找资源。似乎演员是为 Rails 2 制作的,我能找到更好的更新教程吗?
    • 是的,我有一个提问者资源。提问者有很多问题。一个问题属于提问者(提问者属性是姓名和电子邮件)..还有类别资源也有一个问题属于一个类别,一个类别有很多问题。我希望能够一次提交一位用户(提问者)提出的许多问题。谢谢
    • Railscast 不是新的,但它仍然很好,这仍然是您在最新版本的 Rails 中执行此操作的方式(更新版本只是关于如何使用 javascript 使这个更时髦)。
    • 您需要一个单独的控制器用于测验/提问者,然后在该测验/提问者中有一个嵌套形式的问题。 Railscast 应该向您展示如何做到这一点。
    • 我正在关注它
    猜你喜欢
    • 2023-03-10
    • 2021-05-18
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 2018-01-30
    相关资源
    最近更新 更多