javascript - 使用 AJAX 渲染新的 ActiveRecord 结果 - 可能是 Mustache?

标签 javascript ruby-on-rails ajax activerecord mustache

我有一个标准索引 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/

相关文章:

Javascript 不会加载代码的特定部分

mysql - 如何获取 rails 事件记录属性对应的 SQL 值

javascript - 获取 Recaptcha 2 与 PHP 页面通信时出现问题

javascript - 对各种 webpack shimming 方法的困惑

javascript - 在 Ember.js 中,我在哪里放置 Controller 的初始化代码,尝试了路由设置 Controller

ruby-on-rails - 从 Controller 外部销毁资源

ruby-on-rails - 为什么 libnotify 停止显示 Rspec 通知?

javascript - 防止在ajax中重新初始化

javascript - 使用 jQuery Ajax 和 PHP 进行 CORS 请求

javascript - 如何在react js中导入另一个包含图像的组件