Filter result of a collection_select based on the selection of another

0

I need to filter the result of neighborhoods based on the selection of a city. I have a has_many relation through the active record. Is it possible to perform this filter without submitting?

In models:

class Cidade < ApplicationRecord
  has_many :bairros
end

class Bairro < ApplicationRecord
    belongs_to :cidade
end

In view:

<div class="form-group">
    <%= f.label :bairro, "Bairro:", class: "col-sm-2 control-label" %>
    <div class="col-sm-6">
      <%= f.collection_select :bairro_id, @bairros, :id, :nome, {} , class: "form-control" %>
    </div>
  </div>

  <div class="form-group">
    <%= f.label :cidade_id, "Cidade:",class: "col-sm-2 control-label" %>
    <div class="col-sm-6">
     <%= f.collection_select :cidade_id, @cidades, :id, :nome, {} , class: "form-control" %>
    </div>
  </div>
    
asked by anonymous 09.09.2017 / 20:12

1 answer

1

Yes it is possible. I use code similar to grouped_collection_select

If the list is too long, you can still add a jquery for example to change the list according to the first selection.

Here's my example:

<%= f.label :origin_id, "Estado" %>
<%= f.collection_select(:origin_id, State.all, :symbol, :name, {:include_blank => true}, {:class=> "form-control"}) %>

<%= f.label :origin_city_id, "Cidade" %>
<%= f.grouped_collection_select :origin_city_id, State.order(:name), :cities, :name, :name, :name, {include_blank: true}, {:class=> "form-control"} %>
    
26.09.2017 / 20:36