2016-08-01 4 views
1

form_tagを使用して検索フォームにいくつかの動的ドロップダウン選択メニューを設定しようとしています。Rails4 Dynamic Selectドロップダウン

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

A状態にhas_manyサイト私が希望することはRailcasts #88

モデルで発見例と同様の機能です。または反対に、カウントはbelongs_toホストに属していますbelongs_to状態に属するサイト

Stateドロップダウンからホストを介して関連付けられた状態に基づいてサイトをグループ化したいと考えています。

私はこのネストされた関連付けに苦労しており、grouped_collection_selectの構築方法を理解できていないようです。

私は明らかな何かを見落としていることを知っています!いくつかのポインタを使用することができます...

答えて

1

jquery-ajax要求を起動できます。最初の選択ボックスの変更イベントはコントローラ上でアクションを呼び出し、呼び出されたメソッドはajaxコールによって2番目のドロップダウンの値を変更します。簡単な例:ビューファイルで

:そのコントローラの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個までのレベルの検索に行くことができます。がんばろう。

関連する問題