【发布时间】:2014-01-05 07:52:00
【问题描述】:
rails 3.1 runy 1.92 试图允许用户使用产品类型属性过滤产品列表,并在他们做出选择后通过 AJAX 异步更新列表。
我的方法是为每种产品类型创建实例变量,并创建一个实例变量来保存用户选择结果,就像这样
@auto = Product.where(:type =>"auto") #assign all products w/ type=auto to @auto
@filter_selection = @products # this value defaults to all products but would be updated to @auto or @home depending on users selection
我的 Javascript 非常弱,而我的 Ruby 只是稍微好一点,非常感谢任何帮助。
产品型号
class Product < ActiveRecord::Base
attr_accessible :location, :price, :type,
TYPES = ["auto", "home", "garden"]
Store_Controller(注意这是存储控制器而不是产品控制器)
class StoreController < ApplicationController
def index
#instance variables to filter on product type
@auto = Product.where(:type =>"auto")
@home = Product.where(:type =>"home")
@garden = Product.where(:type =>"garden")
@products = products.all
@filter_selection = @products #all products listed by default
#filter Products array based on users selection
@products = @auto if @filter_selection == "auto"
@products = @home if @filter_selection == "home"
@products = @garden if @filter_selection == "garden"
respond_to do |format|
...
end
end
Store_Controller 的索引视图
<div class="products_list">
<%=select_tag "dept-filter", options_from_collection_for_select(@products, "id", "dept"), :prompt => "All Departments", :remote => true%>
<%@products.each do |product|%>
<%=product.price%>
...
</div>
<%end%>
<script>
$(document).ready ->
$("#dept-filter").on "change", ->
$.ajax
type: "GET"
dataType: "script"
data:
dept_type: $("#dept-filter").val()
</script>
索引.js.erb
$('.products_list').html("<%= j render("products_list") %>").fadeIn('slow');
所以我的问题基本上是 1-如何将用户选择的结果绑定到我的 @filter_selection 变量 2-如何通过 AJAX 更新它
【问题讨论】:
标签: ruby-on-rails ajax