我目前在我的网站上_request_form
创建新内容相当复杂。Requests
目前,在创建请求时,员工必须从下拉菜单中选择他们的姓名,如下所示:
<%= f.collection_select :name, Employee.all(:order => 'name'), :name, :name %>
这个选择把右边Employee
放在Request
. 但是,如果员工不在数据库中,我想要一个other
选项,collection_select
它会生成两个文本框(用于 Employeename
和email
),并且在提交表单时会生成新的Employee
.
我认为这需要一些花哨的东西Ajax
,但我有限的 Rails 知识并没有延伸那么远!
编辑:
这是我的完整观点:
<%= javascript_include_tag :defaults, "nested_form" %>
<div class="request_form">
<% if !@request.errors.empty? %>
<div class="alert alert-error">
<ul>
<% @request.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="well">
<%= nested_form_for @request, html: { multipart: true } do |f| %>
<%= f.label :title %><br />
<%= f.text_field :title %><br /><br />
<%= f.label :name, 'Submitted By' %><br />
<%= f.select :name, Employee.sorted_employees_list.map { |value| [ value, value ] }, :id => "employee_box" %><br />
<div id="new_employee_data">
</div>
<%= f.label :description %><br />
<%= f.text_area :description %><br /><br />
<%= f.label :attachment_uploader, 'Attachments' %><%= f.file_field :attachment_uploader, :multiple => true, name: "data_files[attachment_uploader][]" %><br />
<% unless @request.data_files.empty? %>
<%= f.label :attachment_uploader, 'Current Attachments:' %><br />
<% end %>
<%= f.fields_for :data_files do |attachment| %>
<% if !attachment.object.new_record? %>
<%= attachment.label :attachment_uploader, 'Delete: ' + attachment.object.attachment_uploader_url.split("/").last %>
<%= attachment.check_box :_destroy %>
<% end %>
<% end %>
</div>
</div>
<script>
$(document).ready(function(){
$('#employee_box').append("<option>Other</option>");
});
$('#employee_box').change(function() {
if( $('#employee_box').val() === 'other' ) {
$('#new_employee_data').append("<input type='text' id='employee_name' placeholder='Employee Name'> <br/> <br /></input><input type='email' id='employee_email' placeholder='Employee Email'> </input>");
}else {
$('#employee_name').remove();
$('#employee_email').remove();
}
});
</script>
这包括@Kirti 的建议。但是,我似乎无法让它工作!