How to populate a Rails dropdown using json array

I have an Ant Displays page that displays detailed information about various types of ants. There are two recessions on this page, one for the environment: [closed, open] and one for the diet: [sugar, fat, protein].

When you select a parameter from each, it displays the product page depending on the parameters. However, some combinations result in null, for example, the Ant carpenter has no indoor sugar product.

I am trying to fill out drop-down lists based on whether the combination is equal or not. If someone chooses a room, I would like sugar to not appear in the next folder if this combo does not exist.

So far, I have two methods for creating json arrays for available elements only:

def food_sources
  food_sources = Ant.find(params[:ant_id]).product_recommendations.where(environment: params[:environment]).map(&:diet)
  render json: food_sources.to_json
end

def environments
  environments = Ant.find(params[:ant_id]).product_recommendations.where(diet: params[:diet]).map(&:environment)
  render json: environments.to_json
end

For example, if the input

http://localhost:3000/ants/27/food_sources?environment=indoor

in the browser it returns

["sugar","protein"]

bc Ant 27 , .

, rails, - ?

= form_tag ant_product_recommendations_path(@ant.id), id: 'select_box',  method: :get do |form|
  %h3 What food source are they currently feeding on?
  = select_tag :environment, options_for_select([["Select One"], "Indoor", "Outdoor"])
  %h3 
    Locate the nest by following the ants back from their food source.
    %br
    Where is the nest located?
  = select_tag :diet, options_for_select([["Select One"], "Sugar", "Fat", "Protein"])
  = submit_tag "Find Solutions", class: 'submit button' 
  = link_to 'Go Back', '/', class: 'go_back'
+1
1

, , ajax, :

$('#select_box').on('change', function () {
    $.ajax({
        url: "/controller/action",
        type: 'get',
        data: $(this).serialize()
    }).done(function (data) {
        change_select(data);
    });
});

function change_select(data) {
    var json = jQuery.parseJSON(data);
    var options = [];
    json.each(function (key, index) {
        options.push({text: index, value: key});
    });
    $("#select_box").replaceOptions(options);
};

, :

  @food_sources = Ant.find(params[:ant_id]).product_recommendations.where(environment: params[:environment]).map(&:diet)
  respond_to do |format|
    format.json { render json: @food_sources }
  end
+6

All Articles