2016-08-01 96 views
1

我正嘗試使用form_tag在搜索表單中設置一些動態下拉選擇菜單。我想是類似的功能在Railcasts #88Rails4動態選擇下拉列表

模型中發現的例子:

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 

查看:

<%= 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如果網站的has_many其中有許多計數主機。或者相反,Counts belongs_to主機whichs belongs_to屬於國家的網站

因此,我想從狀態下拉菜單中選擇一個狀態,然後根據它們通過主機關聯的狀態對網站進行「分組」。

我一直在與這個嵌套關聯掙扎,似乎無法弄清楚如何構建grouped_collection_select。

我知道我忽略了一些明顯的東西!可以肯定地使用一些指針...

回答

1

你可以激發jquery-ajax請求。第一個選擇框中的更改事件將對控制器調用操作,被調用方法將通過ajax調用更改第二個下拉列表的值。簡單的例子:

在視圖文件:

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

在該控制器的JS文件:

$(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 

在NameOfMethod.js.erb

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

在_site_dropdown.html.erb文件:

<% 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級搜索。祝你好運。