Rails 4,AJAX,js.erb,缺少模板

时间:2015-06-15 18:02:10

标签: javascript ruby-on-rails ajax

我试图让AJAX将模板渲染到索引页面。任何人都可以帮助我理解Rails如何渲染" next.js.erb"而不是寻找" next.html.erb"?

的routes.rb

get 'index' => 'products#index'
get 'next' => 'products#next'

index.html.erb

<%= @products.first.price %>
<%= link_to "Next", action:"next", remote: true %>
<div class="box"></div>

next.js.erb

(".box").html(<%= j render("nextitem") %>

_nextitem.html.erb

<%= @products.second.price %>

在products_controller.rb中:

def index
    @products = Product.all
end

def next
    @products = Product.all
    respond_to do |format|
      format.html { redirect_to root_path }
      format.js
    end
end

3 个答案:

答案 0 :(得分:3)

我首先向您的routes.rb页面添加资源路线,而不是指定每条唯一路线:

resources :products, only: [:index] do
    member do
        post 'next'
    end
end

然后您的index.html.erb页面的链接可能如下所示:

<%= link_to "Next", next_product_path(@product), remote: true %>

您的products_controller.rb需要在@product方法中指定一个特定的def next,您可以从@products集合中提取(您可以找到您显示的最新产品和检索下一个,或者你希望这样做。)

然后

next.js.erb可以执行此操作(使_next_item.html.erb部分呈现,将控制器中定义的@product实例变量作为名为product的局部变量传递:

$(".box").html("<%= j render 'nextitem', product: @product %>");

最后在_nextitem.html.erb中,您可以简单地格式化product局部变量,但在呈现之前需要将其放在html中,并替换您当前在页面上的内容,即:

<div><%= product.price %></div>

如果您有任何疑问或有任何不够清楚的地方,请与我们联系!

-Dave

答案 1 :(得分:1)

将next.js.erb更改为:

$(".box").html("<%=j render 'nextitem ' %>")

答案 2 :(得分:0)

如果您只是在/next处请求该页面,则会查找html.erb模板。要呈现js模板,您需要在.js之类的请求末尾添加localhost:3000/next.js。 JSON响应也是如此。对于JSON响应,您需要在URL的末尾添加.json

或者,如果您使用jQuery从服务器获取响应,则需要传递dataType: script以呈现JS格式而不是HTML格式。