Rails4 Dynamic Select Dropdown

↘锁芯ラ 提交于 2019-12-05 05:37:20

问题


I am trying to set up some dynamic Dropdown Select Menus in a Search Form using form_tag. What I would like is similar functionality to the example found at Railcasts #88

Models:

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

View:

<%= 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 State has_many Sites which has_many Hosts which has many Counts. Or conversely, Counts belong_to Host whichs belongs_to Site which belongs to State

So I would like to select a state from the States dropdown that would then "group" the Sites based on the state they associate through the Host.

I have struggled with this nested association and can't seem to figure out how build the grouped_collection_select.

I know I'm overlooking something obvious! Could sure use some pointers...


回答1:


You can fire jquery-ajax request. Change event in first select box will call action on controller and called method will change the value of second dropdown through ajax call. Simple example:

In your view file:

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

In JS file of that controller:

$(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();
});

});

In NameOfController.rb

def NameOfMethod
  ##no need to write anything
end

In NameOfMethod.js.erb

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

in _site_dropdown.html.erb file:

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

So it will change site dropdown based on selected state dropdown. You can go upto n number of level for searching. Good luck.



来源:https://stackoverflow.com/questions/38708428/rails4-dynamic-select-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!