사람들이 질문을 작성할 수있는 설문 조사 앱이 있습니다. 사용자가 새 질문을 만들면 응답 옵션을 제공 할 수도 있습니다. 예를 들어. 질문 : 하늘은 어떤 색입니까? 답변 옵션 : 파랑, 빨강, 자주색.레일 4 : 동일한 모델의 여러 인스턴스를 단일 양식으로 저장
지금, 단일 양식을 사용하여 질문 모델 및 옵션 모델을 만들 수 있지만 같은 양식에서 여러 옵션을 만들고 싶습니다.
사용자가 해시 배열을 제출하고 해당 배열을 반복하여 각 옵션 모델 레코드를 만들 수있는 무제한 form_tag를 만들어야합니까? 아니면 다른 방법이 있습니까?
option.rb
class Option < ActiveRecord::Base
belongs_to :question
end
question.rb
class Question < ActiveRecord::Base
has_many :options
accepts_nested_attributes_for :options
end
질문 컨트롤러
class QuestionsController < ApplicationController
def new
@question = Question.new
@question.options.build
end
def create
@question = Question.new(question_params)
if @question.save
redirect_to @question
else
render 'new'
end
end
private
def question_params
params.require(:question).permit(:title, :desc, options_attributes:[:id, :scope, :option, :question_id])
end
end
_form.html.erb
<%= form_for @question do |f| %>
<%= f.text_field :question, class: "form-control", placeholder: "Survey Question?" %>
<%= f.fields_for :options do |u| %>
<%= u.text_field :option, class: "form-control", placeholder: "Answer Option 1", id: "answer"%>
<%= u.text_field :option, class: "form-control", placeholder: "Answer Option 2", id: "answer"%>
<%= u.text_field :option, class: "form-control", placeholder: "Answer Option 3", id: "answer"%>
<% end %>
<%= f.submit 'Submit', class: "btn btn-default" %>
,
nested_form을 살펴보세요. 거기에서 모두 분명해질 것입니다. – Richlewis