【问题标题】:Ruby on Rails - Call both html.erb and js.erbRuby on Rails - 调用 html.erb 和 js.erb
【发布时间】:2017-04-22 13:32:11
【问题描述】:

我的目标是用同一个控制器调用 html.erb 和 js.erb 文件,但它只调用我的 html 文件。
我的 js 没有被调用。
控制器/categories_controller.rb

  def index
    respond_to do |format|
      format.html
      format.js
    end
    @categories = Category.order('name ASC')
    @category = params[:category]
end

查看/类别/index.html.erb

<% @categories.each do |c| %>
  <%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}" %>
<% end %>

views/categories/index.js.erb(问题出在这里,这个文件没有被调用)

alert("test");
$("#btn-filter<%=@category%>").attr("class","active");

【问题讨论】:

  • here你可以找到澄清讨论。
  • 另一个有趣的讨论here

标签: javascript jquery ruby-on-rails ruby controller


【解决方案1】:

控制器以请求要求的格式响应,因此,您的链接要求 HTML,而不是 JS,因此控制器以 .html.erb 响应。如果你添加一个调用,像这样:

<%= link_to c.name, show_category_path(category: c.id), :id => "btn-filter#{c.id}", remote: true %>

您的请求将请求 JS(因为 remote: true 属性),控制器将响应 .js.erb

【讨论】:

    【解决方案2】:
    You should add remote: true option
    
    <% @categories.each do |c| %>
      <%= link_to c.name, show_category_path(category: c.id),remote:true, :id => "btn-filter#{c.id}" %>
    <% end %>
    

    它会自动找到 index.js.erb 文件。

    【讨论】:

      【解决方案3】:

      只需将 remote: true 属性添加到 link_to。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-16
        • 1970-01-01
        • 2014-08-24
        • 1970-01-01
        • 2013-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多