【发布时间】:2019-09-23 20:51:14
【问题描述】:
我有一个应用程序,其中Question 模型has_many 与Option 的关系。我还有一个按钮可以在创建问题时添加选项。每个问题只有一个正确答案。因此,当我创建一个问题并单击Add Option 按钮时,会创建新选项,但与之关联的新radio button 具有不同的name。事实上radio button 的名称是question[options_attributes][i][is_answer] 的形式,其中i 是id。据我所知radio buttons 应该有same name 作为一个集合或组工作。那么,即使我为一个问题创建了任意数量的选项,我如何才能使其作为一个小组工作呢?
html.erb
<%= form_for @question do |form| %>
<div class="field">
<%= form.label :body %>
<%= form.text_area :body %>
</div>
<%= form.fields_for :options, question.options.each do |a| %>
<div class="field">
<%= a.label :options %>
<%= a.text_area :body %>
<%= a.radio_button :is_answer, "options" %>
<%= a.check_box :_destroy %>
<%= a.label :_destroy, 'delete' %>
</div>
<% end %>
<%= form.submit 'Add option', :name => "add_option" %>
<%= form.submit 'Delete options', :name => "remove_option" %>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
controller.rb
class QuestionsController < ApplicationController
def new
@question = Question.new
@question.options.build
end
def create
@question = Question.new(question_params)
@question.user = current_user
if params[:add_option]
@question.options.build
else
respond_to do |format|
if @question.save
format.html { redirect_to @question, notice: 'Question was successfully created.' and return }
format.json { render :show, status: :created, location: @question }
else
format.html { render :new }
format.json { render json: @question.errors, status: :unprocessable_entity }
end
end
end
render :action => 'new'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_question
@question = Question.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def question_params
params.require(:question).permit(:body, options_attributes: [:id, :body, :question_id, :created_at, :updated_at, :is_answer])
end
end
【问题讨论】:
标签: html ruby-on-rails radio-button