【问题标题】:Rails 3 Filter Array values in View with AJAXRails 3 使用 AJAX 在视图中过滤数组值
【发布时间】: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


    【解决方案1】:

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

      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>
    

    【讨论】:

    • 谢谢@mohamed yakot 这似乎让我走上了正确的道路,但现在当我加载页面时所有产品都丢失了,下拉菜单只显示提示。我也应该对视图进行更改吗?我想我可能需要将用户选择绑定到“@filter_selection”。有关如何执行此操作的任何建议?
    • 仍然没有运气,更新和以前一样。还有其他建议吗?我的 index.js.erb 文件中的代码是否正确?
    猜你喜欢
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多