How to Use Create Ajax Dropdown From Database Models in Rails

- - posted in Technical | Tagged as ajax,rails,dropdown | Comments

This post is about quick demo of Ajax based dropdown in rails. The dropdown fetches the data from a collection in database.

index.html.erb


1
2
3
4
5
6
<div>
<%= f.collection_select :vertical, @verticals, :vertical, :vertical, {:prompt => "Select a Vertical"}, {:class => "dropdown_vertical btn btn-default dropdown-toggle"} %>

<%= f.collection_select :subVertical, @subVerticals, :subVertical, :subVertical, {:prompt => "Select a Sub Vertical"}, {:class => "dropdown_subVertical btn btn-default dropdown-toggle"} %>

</div>

custom.js


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$("#search_vertical").on('change', function(){
var listitems = [];

$.ajax({
      url: "populate_subVerticals",
      type: "GET",
      data: {vertical_name: $(this).val()},
      success: function(data) {
      $("#search_subVertical").children().remove();
      $("#search_subVertical").append('<option value=>' + "Select a Sub Vertical" + '</option>');
      $.each(data,function(key, value) 
      {
      listitems += '<option value="' + value.subVertical + '">' + value.subVertical + '</option>';
      });

      $("#search_subVertical").append(listitems);

      }
  })
});

Controller


1
2
3
4
5
6
7
def populate_subVerticals
    vertical_name = params[:vertical_name]
    @verticals = Vertical.where(:vertical => vertical_name).select("id","subVertical").all
    respond_to do |format|
      format.json { render json: @verticals }
    end
  end

routes.rb file


1
get 'populate_subVerticals', to: 'verticals#populate_subVerticals'

That's it folks.





Gravatar of Ashwani Kumar

Recent posts


Subscribe



Your Feedback encourages me




Learning and Developments

One Month Rails



, AWS Facebook Flash, Forwarding, GOD,Chat,Coffee Github,Feedback,Repo Google,Search HAProxy, IOT, IP-block JQuery Load MQ MQTT, Messaging Octopress Octopress, Plugin Plugin, Port S3, SSH, Shell,Commands Soapui, Tag Tag, Tree, Tunneling XML XML, XServer, Xming ajax, angular, animated balancing cloud, commenting, connectivity datatables diaspora dropdown geocoding grep, ipaddress, ipv6, java, mysql nokogiri, octopress-migration octopress-plugin openssl powershell rails, repo reviews ruby, script scripts, security, sharepoint shell ssh, telnet, vi, vieditor vim, visualblock, webattacks windows,cleanup windowsxp