使用AJAX(可能是Mustache)呈现新的ActiveRecord结果

Render new ActiveRecord results using AJAX - potentially Mustache?

本文关键字:结果 ActiveRecord Mustache AJAX 使用      更新时间:2023-09-26

我有一个标准索引视图,它遍历来自控制器的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文件/AAJAX响应中的索引视图重建相同的结构似乎是可能的,但不是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 %>")

希望这对你有帮助。