【问题标题】:Why does Rails not recognize a *.js.coffee template?为什么 Rails 不能识别 *.js.coffee 模板?
【发布时间】:2020-04-09 02:15:51
【问题描述】:

我正在关注“使用 Rails 5.1 进行敏捷 Web 开发”一书。有一个关于使用 Ajax 的部分,用于在不重新加载页面的情况下更新“购物车”模型。

这里是控制器app/controllers/line_items_controller.rb

def create
    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product)

    session[:counter] = 0

    respond_to do |format|
      if @line_item.save
        format.html { redirect_to store_index_url }
        format.js { @current_item = @line_item }
        format.json { render :show, status: :created, location: @line_item }
      else
        format.html { render :new }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

书上说上面函数中respond_to的函数会导致create.js.coffee模板被执行。

这里是app/views/line_items/create.js.coffee

cart = document.getElementById("cart")
cart.innerHTML = "<%= j render(@cart) %>"

最后,将商品添加到购物车的按钮定义如下:

<%= button_to 'Add to Cart', line_items_path(product_id: product), remote: true %>

书上说remote: true 部分会导致页面无法重新加载。

使用名为create.js.coffee 的文件,购物车根本不会像应有的那样更新。但是,当我将文件重命名为 create.js.erb 时,我确实看到购物车异步刷新而没有重新加载页面。什么给了?

当文件命名为create.js.coffee 时,我收到的日志消息是No template found for LineItemsController#create, rendering head :no_content

当文件命名为create.js.erb 时,我看到模板已找到并呈现。

【问题讨论】:

    标签: ruby-on-rails ajax coffeescript


    【解决方案1】:

    我需要添加 coffee-rails gem。我不知道为什么我还没有这个 - 我使用的是 Rails 6.0.1。

    【讨论】:

    • Rails 默认不再附带 Coffeescript。它真的已经过时了,因为 ES6 具有区分 CS 的大部分特性,而没有与用另一种编译成 JS 的语言编写相关的所有问题。正在进行从所有指南中删除咖啡脚本的工作。 github.com/rails/rails/issues/37742
    猜你喜欢
    • 2016-10-08
    • 1970-01-01
    • 2019-11-07
    • 2014-10-28
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多