Rails 3.2.2 not executing rjs

Rails 3.2.2 not executing rjs

本文关键字:rjs executing not Rails      更新时间:2023-09-26

我正在关注《Pragmatic Agile Web Development with Rails 4th Edition》一书,但我使用的是Rails 3.2.2而不是书中推荐的3.0.5:

~$ ruby -v
ruby 1.9.3p125 (2012-02-16) [i686-linux]
~$ rails -v
Rails 3.2.2

在包含 AJAX 以重新绘制购物车而不重新加载页面时,我遇到了困难。以下是 line_items_controller.rb 中的创建操作:

def create
    @cart = current_cart
    product = Product.find(params[:product_id])
    @line_item = @cart.add_product(product.id)
    respond_to do |format|
      if @line_item.save
        format.html { redirect_to(store_url) }
        format.js 
        format.json { render json: @line_item, status: :created, location: @line_item }
      else
        format.html { render action: "new" }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

这是我的RJS文件create.js.rjs(在app/views/line_items下):

page.alert('NO PROBLEM HERE')
page.replace_html('cart', render(@cart))

但是,当我单击启动此操作的按钮时:

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

我在开发日志中收到以下错误:

ActionView::MissingTemplate (Missing template line_items/create, application/create with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
  * "/home/me/src_rails/depot/app/views"
):
  app/controllers/line_items_controller.rb:47:in `create'

如果我将create.js.rjs的文件名更改为create.js.erb,则问题已得到纠正:

Rendered line_items/create.js.erb (0.4ms)

但是视图中什么也没发生。甚至没有警报。我错过了什么?file.js.erb 和 file.js.rjs 有什么区别?

看起来rjs已被删除为Rails 3.1的默认值。您可以通过安装 prototype-rails gem 来恢复它,但我认为您应该只使用 jQuery,这是新的默认值。

至于你的代码,它不起作用的原因是它是一个被解释为.js.erb rjs模板,这可能只是产生无效的JavaScript(你应该在浏览器的JavaScript控制台中看到错误)。一个rjs模板,用于为您设置 page 变量,您可以使用它编写 Ruby 代码来操作您的页面。在 .js.erb 模板中,它的工作方式更像在.html.erb视图中。你编写实际的JavaScript,使用<% %>标签嵌入Ruby。因此,create.js.erb中的代码应如下所示:

 alert('NO PROBLEM HERE');
 $('#cart').html("<%= escape_javascript(render(@cart)) %>");

在 rails>= 3.1 中,不再有 jquery-rjs。但是你可以在这里使用CoffeeScript: line_items/create.js.coffee

alert 'NO PROBLEM HERE'
$('#cart').html '<%= j render(@cart) %>'

或类似的东西。