【问题标题】:How to populate a Rails dropdown menu with a json array如何使用 json 数组填充 Rails 下拉菜单
【发布时间】:2013-10-15 23:03:17
【问题描述】:

我有一个蚂蚁展示页面,其中显示了有关各种蚂蚁的详细信息。在该页面上有两个下拉菜单,一个用于环境:[室内、室外],另一个用于饮食:[糖、脂肪、蛋白质]。

当您从每个参数中选择一个参数时,它会根据参数呈现一个产品页面。但是,有些组合会导致 nil,例如木蚁没有与室内糖相关的产品。

我正在尝试根据组合是否为零来填充下拉列表。如果有人选择室内,如果该组合不存在,我希望糖不会出现在下一个下拉菜单中。

到目前为止,我有两种方法只为可用项目创建 json 数组:

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

例如,如果输入

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

进入它返回的浏览器

["sugar","protein"]

对于 id 为 27 的蚂蚁来说,bc 只有两个户外室内饮食选项,而不是可能的三个。

我的问题是,如果有人选择了上述组合,我如何将此数组传递到我的 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'

【问题讨论】:

  • 为什么是 json 而不是 ajax 调用?
  • 没有理由。这是我的第一个理论。我愿意接受建议。
  • 在我看来,Json 应该与 Ajax 调用一起使用
  • 允许这样的开放式查询是个好主意还是坏主意?

标签: javascript ruby-on-rails json jquery


【解决方案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

【讨论】:

  • 这段代码将充满漏洞,但我希望它向您展示了您可以做些什么来实现您的目标:)
  • 感谢您的帖子!视图会是什么样子。我会将我的表单 haml 发布到我的原始帖子中。
  • 好的,不需要我的编辑。您当前的表单似乎还可以(如果它包含您想向人们展示的下拉选项?)。动态选项的附加应该由 javascript 完成,但我想最大的问题是如何做到这一点,以便用户可以将选择恢复为原始选项。如果你愿意,我可以聊聊吗?
  • 我很想和你谈谈。如果你有时间。很抱歉我不在办公桌前。
  • 对不起!我丢失了链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-19
  • 2013-08-12
  • 1970-01-01
  • 2016-08-15
  • 2023-04-05
  • 1970-01-01
  • 2013-08-23
相关资源
最近更新 更多