2016-08-01 3 views
1

form_tag를 사용하여 검색 양식에 일부 동적 드롭 다운 선택 메뉴를 설정하려고합니다. 내가하고 싶은 것은 Railcasts #88Rails4 Dynamic Select Dropdown

모델에서 발견 된 예와 유사한 기능입니다 :

class Count < ActiveRecord::Base 
    belongs_to :host 
end 

class Host < ActiveRecord::Base 
    belongs_to :site 
    has_many :counts 
end 

class Site < ActiveRecord::Base 
    belongs_to :state 
    has_many :hosts 
end 

class State < ActiveRecord::Base 
    has_many :sites 
end 

보기 : has_many 많은 카운트가 호스트

<%= form_tag(counts_path, :method => "get", id: "search-form") do %> 
    <%= select_tag "state_id", options_from_collection_for_select(State.all.order(:name), :id, :name) %> 
    <%= select_tag "site_id", options_from_collection_for_select(Site.all.order(:name), :id, :name) %> 
<% end %> 

상태 has_many 사이트. 또는 반대로, counts belongs_to 호스트가 속한 belongs_to 상태의 사이트

그래서 상태 드롭 다운에서 호스트를 통해 연결된 상태에 따라 사이트를 "그룹화"하고 싶습니다.

나는이 중첩 된 연결에 어려움을 겪었으므로 grouped_collection_select를 빌드하는 방법을 파악할 수 없습니다.

나는 명백한 것을 간과하고 있다는 것을 알고있다! 확실하게 몇 가지 포인터를 사용할 수 ...

답변

1

jquery-ajax 요청을 실행할 수 있습니다. 첫 번째 선택 상자에서 변경 이벤트는 컨트롤러에서 작업을 호출하고 호출 된 메서드는 아약스 호출을 통해 두 번째 드롭 다운 값을 변경합니다. 간단한 예 : 뷰 파일에서

: 해당 컨트롤러의 JS 파일에서

<%= select_tag 'state_id', options_for_select(State.all.order(:name), :id, :name) %> 

<%= select_tag "site_id", options_for_select(Site.all.order(:name), :id, :name) %> 

:

$(document).on('ready page:load', function() { 
$('#state_id').change(function(event){ 
     $("#site_id").attr('disabled', 'disabled')   
     $.ajax({ 
    type:'post', 
    url:'/NameOfController/NameOfMethod', 
    data:{ state_id: $(this).val() }, 
    dataType:"script" 
    }); 
    event.stopImmediatePropagation(); 
}); 

}); NameOfController.rb에서

def NameOfMethod 
    ##no need to write anything 
end 

_site_dropdown.html.erb 파일 NameOfMethod.js.erb

<% if params[:state_id].present? %> 
    $("#site_id").html("<%= escape_javascript(render(partial: 'site_dropdown'))%>") 
<% end %> 

에서 :

<% if params[:state_id].present? %> 
    <%= select_tag 'site_id', options_for_select(Site.where("state_id = ?", params[:state_id])) %> 
<% else %> 
    <%= select_tag "site_id", options_for_select(Site.all.order(:name), :id, :name) %> 

그래서 사이트를 변경됩니다 선택된 상태 드롭 다운에 기반한 드롭 다운. 검색을 위해 n 개의 레벨까지 갈 수 있습니다. 행운을 빕니다.