2016-08-01 100 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级搜索。祝你好运。