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.