我对使用Rails 5的红宝石不熟悉,我试图制作一个“调查应用程序”,使用户能够将问题作为动态形式动态添加到调查中。我设法使其运行,但“添加问题”按钮未添加问题表单,“删除”按钮未删除问题表单。
填写字段并单击提交按钮后,它仅保存用户group
属性,该属性是我在调查模型中指定的。
任何人都可以协助您在表格中添加更多问题并由用户删除吗?
models / survey.rb
class Survey
include Mongoid::Document
has_many :questions, dependent: :destroy
accepts_nested_attributes_for :questions, allow_destroy: true
field :group_id, type: String
end
models / question.rb
class Question
include Mongoid::Document
field :qtype, type: String
field :tittle, type: String
field :qline, type: String
belongs_to :survey, optional: true
end
controllers / survey_controller.rb
def new
@survey = Survey.new
@survey.questions.build
end
def create
@survey = Survey.new(survey_params)
respond_to do |format|
if @survey.save
format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
format.json { render :show, status: :created, location: @survey }
else
format.html { render :new }
format.json { render json: @survey.errors, status: :unprocessable_entity }
end
end
end
surveys / form.html.erb
<%= form_for(@survey) do |f| %>
<div class="field-input">
<%= f.label :group_id %><br>
<%= f.text_field :group_id %>
</div>
<table class='table'>
<thead>
<tr>
<th></th>
<th>question type</th>
<th>tittle</th>
<th>write question</th>
</tr>
</thead>
<tbody class='fields'>
<%= f.fields_for :questions do |builder| %>
<%= render 'question', f: builder %>
<% end %>
</tbody>
</table>
<div class="actions">
<%= f.button :submit %>
<%= link_to_add_row('Add Question', f, :questions, class: 'btn btn-
primary') %>
</div>
<% end %>
_question.html.erb
<tr>
<td>
<%= f.hidden_field :_destroy, as: :hidden %>
<%= link_to 'Delete', '#', class: 'remove_record' %>
</td>
<td><%= f.text_field :qtype, label: true %></td>
<td><%= f.text_field :tittle, label: false %></td>
<td><%= f.text_field :qline, label: false, as: :string %></td>
</tr>
_application_helper.rb
module ApplicationHelper
def link_to_add_row(name, f, association, **args)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize, f: builder)
end
link_to(name, 'new', class: "add_fields " + args[:class], data: {id: id, fields: fields.gsub("\n", "")})
end
end
脚本
$(document).on('turbolinks:load', function() {
$('form').on('click', '.remove_record', function(event) {
$(this).prev('input[type=hidden]').val('1');
$(this).closest('tr').hide();
return event.preventDefault();
});
$('form').on('click', '.add_fields', function(event) {
var regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$('.fields').append($(this).data('fields').replace(regexp, time));
return event.preventDefault();
});
});