hac*_*att 3 collections ruby-on-rails model-associations
我正在尝试使用 form_tag 在搜索表单中设置一些动态下拉选择菜单。我想要的是与Railcasts #88 中的示例类似的功能
楷模:
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
Run Code Online (Sandbox Code Playgroud)
看法:
<%= 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 %>
Run Code Online (Sandbox Code Playgroud)
状态 has_many Sites which has_many Hosts 有许多计数。或者相反,计数属于状态的属于主机的属于状态的站点
因此,我想从“状态”下拉列表中选择一个状态,然后根据站点通过主机关联的状态“分组”站点。
我一直在努力解决这个嵌套关联,似乎无法弄清楚如何构建 grouped_collection_select。
我知道我忽略了一些明显的东西!可以肯定使用一些指针...
您可以触发 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) %>
Run Code Online (Sandbox Code Playgroud)
在该控制器的 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();
});
Run Code Online (Sandbox Code Playgroud)
});
在 NameOfController.rb 中
def NameOfMethod
##no need to write anything
end
Run Code Online (Sandbox Code Playgroud)
在 NameOfMethod.js.erb 中
<% if params[:state_id].present? %>
$("#site_id").html("<%= escape_javascript(render(partial: 'site_dropdown'))%>")
<% end %>
Run Code Online (Sandbox Code Playgroud)
在 _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) %>
Run Code Online (Sandbox Code Playgroud)
所以它会根据选择的状态下拉列表更改站点下拉列表。您最多可以进行 n 级搜索。祝你好运。