【问题标题】:Render new ActiveRecord results using AJAX - potentially Mustache?使用 AJAX 渲染新的 ActiveRecord 结果 - 可能是 Mustache?
【发布时间】:2015-12-24 05:54:18
【问题描述】:

我有一个标准的索引视图,它遍历来自控制器的 ActiveRecord 查询的结果:@recipes = Recipe.all 并显示属性。

#index.html.haml
    - @recipes.each do |recipe|
        .card-item      
            .crop= image_tag(recipe.image.url, class: "thumbnail")
            = link_to(recipe) do
                %p.card-title= recipe.title

我正在尝试在此页面上实现过滤功能,用户可以借此缩小搜索结果的范围,并且页面无需重新加载即可更新。我编写了一条新路由,当被过滤器提交命中时,它会获取传递的参数并进行新的 ActiveRecord 查询,例如@results = Recipe.where("favorite": true)

我不知道如何在不重新加载页面的情况下呈现此查询的结果。经过研究,它似乎是 JavaScript 部分或 Mustache 模板,因为 AJAX 响应可能会有所帮助,但我不确定如何实现它。这似乎是一个非常基本的功能,所以我想知道是否有更简单的方法来简单地使用内置的 Rails 功能。从 JS 文件/AJAX 响应中的索引视图重建相同的结构似乎是可能的,但不是 DRY 或高效(在这种小情况下没关系,但我无法想象比这里有更多信息的应用程序这样做) .我基本上想知道最好的解决方案是什么。

【问题讨论】:

    标签: javascript ruby-on-rails ajax activerecord mustache


    【解决方案1】:

    首先你创建一个部分_recipe.html.haml

    app/views/recipes/_recipe.html.haml

    .card-item      
            .crop= image_tag(recipe.image.url, class: "thumbnail")
            = link_to(recipe) do
              %p.card-title= recipe.title
    

    render 它位于您希望在索引页面上的部分中,无需ajax 调用。

    app/views/recipes/index.html.haml

    ##Section where you want to list all recipes
    %div#all_recipes
      = render @recipes
    

    假设您在 search 操作中执行搜索

    def search
      @recipes = Recipe.where(favorite: true)
      respond_to do |format|
        format.js
      end
    end
    

    创建一个search.js.erb 文件并使用搜索结果呈现部分

    app/views/recipes/search.js.erb

    $("#all_recipes").html("<%= j render @recipes %>")
    

    希望这对你有帮助。

    【讨论】:

    • 感谢您的明确答复。但是,看起来 search.js.erb 文件没有被命中。我尝试将一些控制台登录进行测试,但它不起作用(除了未呈现过滤结果之外)。控制台中没有错误,当我单击过滤器时,服务器日志没有显示任何操作。我是否需要直接将该文件包含在任何地方或以某种方式调用它? 编辑我重新添加了 AJAX 调用,但在响应中没有做任何事情,它可以工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    相关资源
    最近更新 更多