在选择下拉列表中使用轨道中的ajax

时间:2013-12-31 19:55:41

标签: jquery ruby-on-rails ajax

我想知道如何使用Ruby / Rails作为练习。

index.html.erb

<div id="selectionsPane">
  <label for="bootChooserControl">Boot style:</label>&nbsp;
  <select id="bootChooserControl" name="bootStyle"></select>
</div>
  <div id="productDetailPane">
  </div>
</div>
<div>
  <label>Item name:</label> <%= @boot.name %>
</div>
...

boots.js

$(function() {

  $('#bootChooserControl').load('/fetch_boot_style_options');

  $('#bootChooserControl').change(function(event){
    $.get(
      '/fetch_product_details',
      {style: $(event.target).val()},
      function(response) {
        $('#productDetailPane').html(response);
        $('[value=""]',event.target).remove();
      }
    );
  });
});

boots_controller.rb

def fetch_product_details
  @boot = Boot.where(sku: params[:style])
  render layout: false
end

fetch_boot_style_options

<option value="">&mdash; choose a style &mdash;</option>
<% @boots.each do |boot| %>
  <option value="<%= boot.sku %>"><%= boot.name %></option>
<% end %>

所以我希望Item Name在我的数据库中填充正确的引导名称。首先,如何使用select方法构建我的选择按钮Rails方式?其次,当用户选择不同的项目时,我希望productDetailsPane更新。我不知道我需要添加什么才能使这段代码准备好Rails / AJAX。

2 个答案:

答案 0 :(得分:1)

使用collection_selectselect_tag在Rails方式中选择菜单 要在选择项目时填充面板,可以使用AJAX调用。 Here是一些资源,它使用JQuery的$.ajax操作来进行调用,并在success执行时执行某些操作。 This is another做类似任务的详细有用的答案。

祝你好运

答案 1 :(得分:0)

boot.js 内取出以下一行:$('#productDetailPane').html(response);

<强> boots_controller.rb

def fetch_product_details
  @boot = Boot.where(sku: params[:style]).first
  respond_to do |format|
    format.js
  end
end

<强> fetch_product_details.rb

$('#productDetailPane').html('<%= j render "product_details" %>');

<强> _product_details.html.erb

<div>
  <label>Item name:</label> <%= @boot.name %>
</div>
<div>
  <label>SKU:</label> <%= @boot.sku %>
</div>
<div>
  <label>Height:</label> <%= @boot.height %>
</div>
<div>
  <label>Colors:</label> <%= raw @boot.colors %>
</div>
<div>
  <label>Lining:</label> <%= @boot.lining %>
</div>
<div>
  <label>Today's price:</label> <%=  number_to_currency(@boot.price) %>
</div>
<div>
  <label>Features:</label> <%= raw @boot.features %>
</div>
<div align="center">
  <% if params[:style] != 'default' %>
    <%= image_tag 'photos/' + @boot.sku.to_s + '.png' %>
  <% end %>
</div>

<强>的routes.rb

get '/fetch_boot_style_options' => 'boots#fetch_boot_style_options'
get '/fetch_product_details' => 'boots#fetch_product_details'