Filter the result of a collection_select based on the selection of another

Asked

Viewed 210 times

0

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

In the 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>

1 answer

1

Yes it is possible. I use a code similar to grouped_collection_select

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

Follow 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"} %>
  • Hi, Cleber, I really appreciate your help. I managed to create the grouped Collection, however, it always lists all the neighborhoods, indifferent to the selected city. Know some way to bring only the neighborhoods filtered by the city already selected?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.