我有一个标准索引 View ,它迭代来自 Controller 的 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 响应中的索引 View 重建相同的结构似乎是可能的,但不是干的或高效的(在这个小情况下,没关系,但我无法想象比这里拥有更多信息的应用程序会这样做) 。我基本上想知道最好的解决方案是什么。
最佳答案
首先创建一个部分_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
渲染
它在索引页面上您想要的部分,而不需要ajax
调用。
app/views/recipes/index.html.haml
##Section where you want to list all recipes
%div#all_recipes
= render @recipes
假设您在搜索
操作中执行搜索
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 %>")
希望这对您有帮助。
关于javascript - 使用 AJAX 渲染新的 ActiveRecord 结果 - 可能是 Mustache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34447971/