如何在Rails中使用CoffeeScript?

zol*_*ter 3 javascript templates ruby-on-rails controller-action coffeescript

在我的控制器的create动作中,我有以下内容:

def create
  @article = Article.find(params[:id])

  respond_to do |format|
    if @comment.save
      format.js { render 'success.js' }
    else
      format.js { render 'failed.js' }
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

在我app/views/comments/failed.js.coffee,我有:

alert 'Write smth!' if $("#comments_error").length == 0
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

ActionView::MissingTemplate (Missing template comments/failed,
  inherited_resources/base/failed, application/failed with
  {:locale=>[:en, :en],
   :formats=>[:js, :html],
   :handlers=>[:haml, :builder, :erb]})
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

kai*_*ain 7

在撰写本文时,Rails不支持使用咖啡脚本文件进行响应.然而,这将发生变化.

同时在你的Gemfile中添加:

gem 'coffeebeans'
Run Code Online (Sandbox Code Playgroud)

然后命名你的观点action.js.coffee

作为额外的奖励,文件将首先通过erb,即使它未在文件名中声明.