使用 AJAX 呈现新的 ActiveRecord 结果 - 可能是 Mustache?

Render new ActiveRecord results using AJAX - potentially Mustache?

我有一个标准索引视图,它遍历来自控制器的 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 file/AJAX 响应中的索引视图重建相同的结构似乎是可能的,但不是 DRY 或高效的(在这种小情况下没关系,但我无法想象比这里有更多信息的应用程序会这样做方法)。我基本上想知道最好的解决方案是什么。

首先你创建一个部分_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 %>")

希望对您有所帮助。