Submit two forms from 1a page
Is it possible to have one view with 2 forms in it and submit both forms at the same time?
I don't want to use nested forms.
For example:
I have :
Model Survey
|_question_id
|_answers_id
Model Question:
|_text
Model Answer
|_text
Is it possible to do that without nested forms? For example I want to create a NEW question (Form 1) and a NEW answer (Form 2) and in the create method in the Controller I will create a new Survey and MANUALLY a开发者_JAVA技巧ssign the question_id and answers_id to the newly created question and answer accordingly!
Thanks
A better approach would be to use accepts_nested_attributes_for
to build all three models via one form submission.
Set your models up like so:
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
Then you can write your form using rails helpers like this:
<%= 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 %>
In the controller action that will render the form you need to build the new records in memory like this:
class SurveyController < ApplicationController
def new
@survey = Survey.new
@survey.build_question
@survey.answers.build
end
end
You can read more about accepts_nested_attributes_for here
: http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
精彩评论