我会在 select 和 UJS 上使用 ajax 来更改从部分加载的内容。
例如
#/railsapp/app/controllers/products_controller.rb
def index
@title= "Home"
if Product.all.collect(&:dept_type) == (params[:dept])
@products= Product.send(params[:dept])
else
@products = Product.order(:premium)
end
respond_to do |format|
format.html # index.html.erb
format.js # index.js.erb
format.json { render json: @products }
end
end
在你看来
#/railsapp/app/views/products/index.html.erb
<%= form_tag('products', :remote => true) do %>
<%= select_tag "dept", options_from_collection_for_select(@products, "id", "dept_type"), { :include_blank => true , :class => "product_select"} %>
<% end %>
<div id="products_list"></div>
然后添加javascript(在这种情况下为咖啡脚本)
#/railsapp/app/assets/javascripts/products.js.coffee
$(document).ready ->
$(".product_select").on "change", ->
$.ajax
url: "/products"
type: "GET"
dataType: "script"
data:
dept_type: $(".product_select").val()
因此,coffeescript 在选择框更改时向产品控制器的索引操作发出 ajax 请求。控制器将渲染 UJS 模板,因为 dataType 是脚本。现在为 UJS
#/railsapp/app/views/products/index.js.erb
$("#products_list").html('<%= j render("product_list") %>').fadeIn('slow');
这只是在部分 product_list 上调用 javascript 转义渲染,其中包括:
#/railsapp/app/views/products/_product_list.html.erb
<%- @products.each do |product| %>
<%= product.name %>
<% end %>
因此,现在您将拥有一个选择框,它在页面加载时呈现 html,在 ajax 请求上呈现 javascript 以确定正确的部门,并在您从下拉列表中更改选择时换出列表。