Ruby on Rails如何实现单页面提交两个表单的优化设计?

2026-04-11 18:181阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计375个文字,预计阅读时间需要2分钟。

Ruby on Rails如何实现单页面提交两个表单的优化设计?

可以设计一个视图,包含两个表格,并同时展示两个表格的数据。但我不想使用嵌套表格。例如:我有:Model | Survey | question_id | answers_id Model Question: | text Model Answer: | text 没有嵌套表格结构,可以这样做。

是否可以在其中包含一个包含2个表单的视图并同时提交两个表单?

我不想使用嵌套表单.

例如:

我有 :

Model Survey |_question_id |_answers_id Model Question: |_text Model Answer |_text

没有嵌套表格可以做到吗?例如,我想创建一个新问题(表单1)和一个新答案(表单2),在Controller中的create方法中,我将创建一个新的Survey并手动将question_id和answers_id分配给新创建的问题并相应地回答!

谢谢

更好的方法是使用accepts_nested_attributes_for通过一个表单提交来构建所有三个模型.

像这样设置你的模型:

Ruby on Rails如何实现单页面提交两个表单的优化设计?

class Survey < ActiveRecord::Base has_one :question has_many :answers accepts_nested_attributes_for :question, :answers end class Question < ActiveRecord::Base belongs_to :survey end class Answer < ActiveRecord::Base belongs_to :survey end

然后你可以使用rails helper编写你的表单,如下所示:

<%= form_for @survey do |form| %> <%= form.fields_for :question do |question_form| %> <%= question_form.text_field :question <% end %> <%= form.fields_for :answers do |answer_form| %> <%= question_form.text_field :answer <% end %> <%= form.submit %> <% end %>

在将呈现表单的控制器操作中,您需要在内存中构建新记录,如下所示:

class SurveyController < ApplicationController def new @survey = Survey.new @survey.build_question @survey.answers.build end end

您可以在此处阅读有关accepts_nested_attributes_for的更多信息:ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

本文共计375个文字,预计阅读时间需要2分钟。

Ruby on Rails如何实现单页面提交两个表单的优化设计?

可以设计一个视图,包含两个表格,并同时展示两个表格的数据。但我不想使用嵌套表格。例如:我有:Model | Survey | question_id | answers_id Model Question: | text Model Answer: | text 没有嵌套表格结构,可以这样做。

是否可以在其中包含一个包含2个表单的视图并同时提交两个表单?

我不想使用嵌套表单.

例如:

我有 :

Model Survey |_question_id |_answers_id Model Question: |_text Model Answer |_text

没有嵌套表格可以做到吗?例如,我想创建一个新问题(表单1)和一个新答案(表单2),在Controller中的create方法中,我将创建一个新的Survey并手动将question_id和answers_id分配给新创建的问题并相应地回答!

谢谢

更好的方法是使用accepts_nested_attributes_for通过一个表单提交来构建所有三个模型.

像这样设置你的模型:

Ruby on Rails如何实现单页面提交两个表单的优化设计?

class Survey < ActiveRecord::Base has_one :question has_many :answers accepts_nested_attributes_for :question, :answers end class Question < ActiveRecord::Base belongs_to :survey end class Answer < ActiveRecord::Base belongs_to :survey end

然后你可以使用rails helper编写你的表单,如下所示:

<%= form_for @survey do |form| %> <%= form.fields_for :question do |question_form| %> <%= question_form.text_field :question <% end %> <%= form.fields_for :answers do |answer_form| %> <%= question_form.text_field :answer <% end %> <%= form.submit %> <% end %>

在将呈现表单的控制器操作中,您需要在内存中构建新记录,如下所示:

class SurveyController < ApplicationController def new @survey = Survey.new @survey.build_question @survey.answers.build end end

您可以在此处阅读有关accepts_nested_attributes_for的更多信息:ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes