根据先前的选择字段值过滤选择字段

时间:2017-08-07 17:14:38

标签: ruby-on-rails ruby ajax drop-down-menu filter

我是RoR的新手,我的应用程序遇到了麻烦。问题在于根据上面的其他选择字段过滤名为“解决方案”的选择字段。

现在,应用程序所做的是从BD检索有关Area,Region,Associated,Solution的所有信息,并使用这些数据填充选择字段。但是,当用户选择区域,区域和关联时,用户希望仅显示该区域中该区域中关联的解决方案。

编辑:

我快到了!我在我的应用程序中做了很多更改。选择字段由控制器操作new和函数“populate_selects”填充,该函数由参数before_action :popula_selects, only: [:new, :edit]调用。创建了一个新函数,以便由AJAX调用并升级“解决方案”字段:

Atendments_Controller  < ApplicationController

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

def new 
  @atend = atendment.new
end

def update_solution #AJAX
  @solutions = atendment.joins(:solution).where("atendment_area_id = ? and atendment_region_id = ? and atendment_assoc_id = ?", params[:atendment_area_id], params[:atendment_region_id], params[:atendment_assoc_id])
  respond_to do |format|
    format.js 
  end
end

private

def populate_selects
  @atendment_area = atendmentArea.where(status: true, user_id: current_user.id)
  @atendment_region = atendmentRegion.where(status: true, user_id: current_user.id)
  @atendment_assoc = atendmentRegionAssoc.where(status: true, assoc_id: current_user.entidade_id).where(atendment_region_id: @atendment_region.map(&:atendment_region_id))
  @solutions = atendment.joins(:solution).where("atendment_area_id = ? and atendment_region_id = ? and atendment_assoc_id = ?", params[:atendment_area_id], params[:atendment_region_id], params[:atendment_region_assoc_id])

  end
end

下面是来自视图的_form.html.erb代码:

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

  <div class="col-xs-6">
    <%= f.select :atendment_area_id, options_for_select(@atendment_area.collect { |c| [ c.atendment_area.name, c.id ] }, 1), {:prompt=>"Área"}, { :class => 'form-control', :required => true, id: 'atendment_atendment_area_id' } %>
      </div>
        <div class="col-xs-6">
          <%= f.select :atendment_region_id, options_for_select(@atendment_region.collect { |c| [ c.atendment_region.name, c.id ] }, 1), {:prompt=>"Região"}, { :class => 'form-control', :required => true, id: 'atendment_atendment_region_id' } %>
        </div>
      </div>
    </div>

    <div class="field">
      <%= f.select :atendment_assoc_id, options_for_select(@atendment_assoc.collect { |c| [ c.atendment_region.name, c.id ] }, 1), {:prompt=>"Associado"}, { :class => 'form-control', :required => true, id: 'atendment_atendment_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: 'atendment_solution_id' } %>
    </div>
  </div>

路由到新功能:

resources :atendments do
collection do
  get :update_solution
  end
end

AJAX函数调用“update_solution”并重置解决方案字段的值(app / assets / javascript / atendment.js.coffee):

show_solutions = ->

$.ajax 'update_solution',
type: 'GET'
dataType: 'script'
data: {
  atendment_area_id: $("#atendment_atendment_area_id").val()
  atendment_region_id: $("#atendment_atendment_region_id").val()
  atendment_assoc_id: $("#atendment_atendment_assoc_id").val()
}
error: (jqXHR, textStatus, errorThrown) ->
  console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
  console.log("OK!")

$(document).ready ->

  $('#atendment_atendment_assoc_id').on 'change', ->
    show_solutions()

所以,我创建了一个.coffee文件来渲染部分,它会将新值返回到“solution”字段“option”标签  (应用程序/视图/ atendment / update_solution.coffee):

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

最后但并非最不重要的是,包含上面提到的“option”标签的html代码的部分(app / views / atendments / _solution.html.erb):

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

出于任何原因,AJAX函数不会在控制台上打印任何内容(也不会出错也不会成功),但它会调用update_solution.coffee文件。关键是,由于错误(500内部服务器错误),它不会更新选项值。我不知道我做错了什么。如果有人可以帮助我,我很感激。

2 个答案:

答案 0 :(得分:0)

我会用JS做这件事,可以想到任何其他方式。

onchange调用的函数,用于更改您需要隐藏或显示的每个字段的显示属性。

答案 1 :(得分:0)

我用以下代码解决了这个问题:

assets / js / atendments.js
我更改了代码,因为最后一个有很多错误。

function getAssociated(){

  var aau_id = $("#atendment_area_user_id").val() 
  var aru_id = $("#atendment_region_user_id").val();

  $.getJSON("/controllers/atendments_controller/getAssociated/"+aru_id,
    function ( callback ) {
    if (callback != "error"){

      var assoc = document.getElementById("atendment_region_associated_id");

      while (assoc.firstChild) {
        assoc.removeChild(assoc.firstChild);
      }

      var i = Object.keys(callback).length -1;

      $("#atendment_region_associated_id").append("<option value=''>Associated</option>");

      while (i >= 0) {
        $("#atendment_region_associated_id").append("<option value='"+callback[Object.keys(callback)[i]]+"'>"+Object.keys(callback)[i]+"</option>");
        i--;
      }
    }
  });
  get_solution_type();
}

function get_solution_type() {

  var ara_id = $("#atendment_region_associated_id").val();

  $.getJSON("/controllers/atendments_controller/getSolution/"+ara_id,
    function ( callback ) {

    if (callback != "error"){

      var sol = document.getElementById("atendment_solution_id");
      while (sol.firstChild) {
        sol.removeChild(sol.firstChild);
      }
      var i = Object.keys(callback).length-1;
      while (i >= 0) {
        $("#atendment_solution_id").append("<option value='"+callback[Object.keys(callback)[i]]+"'>"+Object.keys(callback)[i]+"</option>");
        i--;
      }
    }
  }); 

  var aau_id = $("#atendment_area_user_id").val();

  $.getJSON("/controllers/atendments_controller/getType/"+aau_id,
    function ( callback ) {

    if (callback != "erro"){

      var type = document.getElementById("atendment_type_id");
      while (type.firstChild) {
        type.removeChild(type.firstChild);
      }
      var i = 0;
      while (i < (Object.keys(callback).length)) {
        $("#atendment_type_id").append("<option value='"+callback[Object.keys(callback)[i]]+"'>"+Object.keys(callback)[i]+"</option>");
        i++;
      }
    }
  });
}

$.getJSON向使用JSON响应的控制器执行ajax请求并更新选择字段选项标记。

controllers / atendments_controller
我只是从DB检索数据并返回JSON

def getAssociated
  aru_id = params[:atendment_region_user_id]
  aras = AtendmentRegionAssociated.where("SQL here")

  if aras.present?
    render :json => aras.to_json
  else
    render :json => "error".to_json
  end

end

def getSolution
  ara_id = params[:atendment_region_associated_id]

  sol = Solution.where("SQL here")

  if sol.present?
    render :json => sol.to_json
  else
    render :json => "error".to_json
  end

end

def getType
  aau_id = params[:atendment_area_user_id]
  type = AtendmentType.where("SQL here")

  if type.present?
    render :json => type.to_json
  else
    render :json => "error".to_json
  end

end

更新routes并将javascript函数放在选择字段onchange属性中。现在一切正常:D