Bunun gem karşılığı: "select2-rails"
Model yapımız şu şekilde:
$ rails g model section name
$ rails g model part name section_id: integer
section ve part has_many ilişkisinde (Fakulte seçildiğinde bölümler alt listeye düşecek)
gemfile
gem 'simple_form'
gem "select2-rails"
gem 'bootstrap-sass', '~> 3.1.1.0'
application.css
*= require bootstrap
*= require select2
*= require select2-bootstrap
application.js
//= require select2
routes.rb
resources :sections do
get 'parts_for_section', on: :member
end
resources :parts
parts_controller.rb
def index
@section_form = Part.new
end
section_controller.rb
def parts_for_section
@member_part = Section.find(params["id"]).parts
respond_to do |format|
format.json { render json: @member_part }
end
end
parts/index.html
<%= simple_form_for @section_form do |f| %>
<div class="form-inputs">
<div class="row form-group">
<label class="control-label col-md-1 col-sm-1 col-xs-1">Fakulte:</label>
<div class="col-md-9 col-sm-9 col-xs-9">
<%= f.input :section_id, collection: Section.all.flat_map { |section| [[section.name, section.id]] }, label: false, prompt: 'Fakulte Seçiniz', :input_html => {:style=> 'width: 300px', :id => "section_for_part" } %>
</div>
</div>
<div class="row form-group">
<label class="control-label col-md-1 col-sm-1 col-xs-1">Bölüm</label>
<div class="col-md-9 col-sm-9 col-xs-9">
<%= f.input :id,:collection => [],:label_method => :name,:value_method => :id, label: false, prompt: 'Bölüm Seçiniz', :include_blank => false, :input_html => { :style=> 'width: 300px',:id => "choose_part" } %>
</div>
</div>
<%end%>
assets/javascript/ altına section.coffee oluşturalım:
$ ->
$('#section_for_part').select2
theme: "bootstrap"
$('#choose_part').select2
theme: "bootstrap"
$('#section_for_part').on 'select2:select', (e) ->
sectionId = $(this).val()
url = "/sections/#{sectionId}/parts_for_section"
console.log sectionId
if sectionId != ""
$.ajax
url: url
type: 'GET'
dataType: 'json'
success: (response) ->
$('#choose_part').empty()
html = ''
$.each response, (key, value) ->
html += "<option value='#{value.id}'>#{value.name}</option>"
return
$('#choose_part').append html
return
çalıştırıp bakalım:
Eğer select2 listesini modal da görüntülenen bir ekranda kullanıyorsanız. modal classının oldugu yerdeki tabindex="-1" ifadesini kaldırmanız gerekiyor
Hiç yorum yok:
Yorum Gönder