我想知道如何使用Ruby / Rails作为练习。
index.html.erb
<div id="selectionsPane">
<label for="bootChooserControl">Boot style:</label>
<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="">— choose a style —</option>
<% @boots.each do |boot| %>
<option value="<%= boot.sku %>"><%= boot.name %></option>
<% end %>
所以我希望Item Name
在我的数据库中填充正确的引导名称。首先,如何使用select
方法构建我的选择按钮Rails方式?其次,当用户选择不同的项目时,我希望productDetailsPane
更新。我不知道我需要添加什么才能使这段代码准备好Rails / AJAX。
答案 0 :(得分:1)
使用collection_select
或select_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'