我想知道如何通过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。
在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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句