Rails 3使用AJAX在View中过滤数组值

时间:2014-01-04 22:29:02

标签: ruby-on-rails ajax

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>

Index.js.erb

 $('.products_list').html("<%= j render("products_list") %>").fadeIn('slow');

所以我的问题基本上都是 1-如何将用户选择的结果绑定到我的@filter_selection变量 2-如何通过AJAX进行更新

1 个答案:

答案 0 :(得分:0)

在产品型号中使用此代码:

  def self.filer_by(type)
   Product.where(type: type)
  end

在商店控制器中使用:

@products = Product.filer_by(@filter_selection)

尝试在Ajax请求中执行此操作:

<script>
 $(document).ready ->
   $("#dept-filter").on "change", ->
   $.ajax
    type: "GET"
    dataType: "script"
    url: 'stores/index', 
    data:
      dept_type: $("#dept-filter").val()
 </script>