为什么Rails无法识别* .js.coffee模板?

时间:2019-12-16 15:28:15

标签: ruby-on-rails ajax coffeescript

我正在关注《用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时,我看到已找到并渲染了模板。

1 个答案:

答案 0 :(得分:0)

我需要添加coffee-rails宝石。我不确定为什么我还没有这个-我正在使用Rails 6.0.1。

相关问题