Filter select fields using the value of other selects with Ruby on Rails

1

Good afternoon, I have a problem to solve here in my application. The problem is to filter the HTML "Solution" select field, based on the values of the other selects fields above it. The image shows an example of these fields.

Currently,theapplicationispullingthedatabasevaluesfortheArea,Region,Associate,andSolutiontables,andthrowingallareas,regions,associates,andsolutionsinthefields.Whattheuserwantstobechangedisthatwhenheselectsanarea,aregionandanassociate,the"Solution" field shows only the solutions for the associated one that is in that region and within that area.

Edit:

I'm almost there! I made several changes to my application. The form fields in the above image are populated by action: new and by popula_selects method that is called by the before_action :popula_selects, only: [:new, :edit] parameter. I created a new method to be called by AJAX and update the "Solution" field. Here are the codes below:

    Atendiments_Controller  < ApplicationController

      before_action :popula_selects, only: [:new, :edit]

        def new 
            @atend = Atendiment.new
        end

        def atualiza_solucao #AJAX
            @solutions = Atendiment.joins(:solution).where("atendiment_area_id = ? and atendiment_region_id = ? and atendiment_assoc_id = ?", params[:atendiment_area_id], params[:atendiment_region_id], params[:atendiment_assoc_id])
            respond_to do |format|
              format.js 
          end
        end

        private

        def popula_selects
              @atendiment_area = AtendimentArea.where(status: true, user_id: current_user.id)
              @atendiment_region = AtendimentRegion.where(status: true, user_id: current_user.id)
              @atendiment_assoc = AtendimentRegionAssoc.where(status: true, assoc_id: current_user.entidade_id).where(atendiment_region_id: @atendiment_region.map(&:atendiment_region_id))
              @solutions = Atendiment.joins(:solution).where("atendiment_area_id = ? and atendiment_region_id = ? and atendiment_assoc_id = ?", params[:atendiment_area_id], params[:atendiment_region_id], params[:atendiment_region_assoc_id])

   end
end

Form Code (app / views / atendiments / _form.html.erb

<div class="atendiment-form">
  <%= form_for :atendiment, url: {action: "new"}, html: {method: "get"} do |f| %>

  <div class="col-xs-6">
    <%= f.select :atendiment_area_id, options_for_select(@atendiment_area.collect { |c| [ c.atendiment_area.name, c.id ] }, 1), {:prompt=>"Área"}, { :class => 'form-control', :required => true, id: 'atendiment_atendiment_area_id' } %>
      </div>
        <div class="col-xs-6">
          <%= f.select :atendiment_region_id, options_for_select(@atendiment_region.collect { |c| [ c.atendiment_region.name, c.id ] }, 1), {:prompt=>"Região"}, { :class => 'form-control', :required => true, id: 'atendiment_atendiment_region_id' } %>
        </div>
      </div>
    </div>

    <div class="field">
      <%= f.select :atendiment_assoc_id, options_for_select(@atendiment_assoc.collect { |c| [ c.atendiment_region.name, c.id ] }, 1), {:prompt=>"Associado"}, { :class => 'form-control', :required => true, id: 'atendiment_atendiment_assoc_id' } %>
    </div>
    <div class="field">
      <%= f.select :solution_id, options_for_select(@solutions.collect { |solution| [solution.name, solution.id] }, 0), {:prompt=>"Solução"}, { :class => 'form-control', :required => true, id: 'atendiment_solution_id' } %>
    </div>
  </div>

Route to the new method:

resources :atendiments do
collection do
  get :atualiza_solucao
  end
end

I created a JQuery Ajax function to call the new method and refresh the Solution field (app / assets / javascript / atendiment.js.coffee)

exibe_solucoes = ->

$.ajax 'atualiza_solucao',
type: 'GET'
dataType: 'script'
data: {
  atendiment_area_id: $("#atendiment_atendiment_area_id").val()
  atendiment_region_id: $("#atendiment_atendiment_region_id").val()
  atendiment_assoc_id: $("#atendiment_atendiment_assoc_id").val()
}
error: (jqXHR, textStatus, errorThrown) ->
  console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
  console.log("OK!")

$(document).ready ->

  $('#atendiment_atendiment_assoc_id').on 'change', ->
    exibe_solucoes()

I then created a .coffee file to render the partial that will update the Solution field (app / views / atendiment / update_solucao.coffee)

$("#atendiment_solution_id").empty()
  .append("<%= escape_javascript(render :partial => 'solucao') %>")

And finally, I created the partial that will be rendered and will be placed in the "option" tag of the "solution" field (app / views / atendiments / _solution.html.erb

<option value="<%= solution.id %>" selected="selected"><%= solution.nome %></option>

However, for some reason the partial is not rendered and the "solution" field is empty (probably because of the empty() method.) In the console, you can see the error " 500 (Internal Server Error) "I do not know why it is giving this error. One thing I noticed is that the application does not print nor what is in%% of the" error "in the AJAX function, nor what is in" success. " thing I realized is that when I change the html of the partial "solution", doing something like this:

<option value="foo" selected="selected">bar</option>

It works and displays "bar" in the "Solution" field. Only with the embedded ruby code it does not work ... If anyone can give me an idea of what to do, thank you very much.

NOTE: I am using version 4.2.1 of rails in this application. Thanks for the attention of everyone and the time dedicated to reading this question, which has been longer than it should have been.

    
asked by anonymous 07.08.2017 / 17:43

2 answers

2

Thanks for the answers personally. I solved this problem by creating a Ajax function that calls a method in controller which searches the DB for the data I need to play in the select fields and returns in JSON format. So, I get this JSON and update the option of the select fields. The code can be seen in this link , which is the same question, but it's in stackoverflow in English.

    
25.10.2017 / 21:50
0

There's an episode of RailsCast that discusses the Dynamic Select Menus , have you taken a look?

Maybe these links are also useful:

link link

They are in English, but nothing that google translator can not help. The first link is aimed more pro ajax, and the second pro js.

    
19.09.2017 / 21:21