简体   繁体   中英

Rails - Drop down list with 'other' that allows creation of new model object

I currently have a rather complicated _request_form for creating new Requests in my website. Currently, when creating a request, employees must choose their name from a dropdown menu like so:

<%= f.collection_select :name, Employee.all(:order => 'name'), :name, :name %>

This selects puts the right Employee in the Request . However, on the off chance the employee isn't in database I'd like an other option in the collection_select that spawns two textboxes (for Employee name and email ), and upon form submission makes the new Employee .

I assume this requires some sort of fancy Ajax , but my limited Rails knowledge doesn't extend that far!

Edit:

Here's my full view:

<%= 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>

This includes @Kirti's suggestion. However, I can't seem to make it work!

Popup dialog is good choice, I think!

1) Add to your Gemfile, and run bundle:

gem 'jquery-ui-rails'

2) Activate jquery-ui javascript (application.js):

//= require jquery.ui.dialog

3) Link jquery-ui stylesheets (application.css):

  *= require jquery.ui.dialog

4) Prepare data for select (employees_controller.rb)

  def new
    @prices = Price.all.map{|p| [p.price, p.id] }
    @prices << ['Create New', 'new_id']    
  end

5) Display select component on view (employees/new.html.erb):

  <%= select_tag :employee, options_for_select(@employees) %>

  <div id="new_employee_dialog">
    <label for="name"   type="text">Employee name:</label>
    <input name="name"  type="text"/>
    <label for="email"  type="text">Employee email:</label>
    <input name="email" type="email"/>
  </div>

6) This javascript work with dialog window and send ajax request (assets/javascripts/employees.js.coffee):

$ ->
    $("#new_employee_dialog").dialog
      modal: true
      width: 400
      height: 300
      autoOpen: false
      draggable: false
      dialogClass: "without-header"
      buttons: [
        text: "Cancel"
        click: ->        
          $(this).dialog "close"
      ,
        text: "Ok"
        click: ->
          modalForm = $(this)
          $.post "/users/form_create",
            employee_name: $(modalForm).find("input[name='name']").val()
            employee_email: $(modalForm).find("input[name='email']").val()          
          , (data, status) ->          
            if data['status'] == 'ok'
              modalForm.dialog "close"
              alert "Ok"
            else
              alert "Oops"
      ]

    $('#employee').change ->
      selected_employee_id = jQuery("#employee").val()
      console.log('selected id: ' + selected_employee_id )
      if selected_employee_id == 'new_id'
        $("#new_employee_dialog").dialog("open");

7) Create method to catch ajax request on server-side (employees_controller.rb):

def form_create
    employee_name = params[:employee_name]
    employee_email = params[:employee_email]
    # create new user..
    respond_to do |format|
      format.json { render :json => {status: 'ok'} }
    end
  end

8) Add it to routes.rb:

  post 'users/form_create' => 'users#form_create'

在此处输入图片说明

Add an empty div tag(placeholder) where you want to spawn the two input fields:

<div id="new_employee_data">

</div>

Add the following jQuery at the bottom of the view:

<script>
$(document).ready(function(){
  $('#request_name').append("<option value='other'>Other</option>");
});

$('#request_name').change(function() {
  if( $('#request_name').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>

where, replace #request_name with the id generated for your collection_select .

You will also need to add code for creating the new employee in the action which is executed at form submission.

NOTE: I am no expert in AJAX but you could adapt the above jQuery and take it from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM