2012-04-13 60 views
9

我正在关注的书务实敏捷Web开发使用Rails第四版,但我用Rails 3.2.2,而不是3.0.5在书中建议:的Rails 3.2.2不执行RJS

~$ 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(在应用程序/视图/ 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有什么不同?

+0

嘿家伙!我在谷歌上找到你的帖子。我面临同样的情况。你找到解决方案吗? – code4j 2012-08-31 20:09:39

+0

我修复了这个问题!看到我的[解决方案](http://stackoverflow.com/questions/12220816/the-ajax-request-cannot-see-the-effect-without-refresh-the-browser-in-rails/12224196#12224196)。我希望这可以帮助你。 – code4j 2012-09-01 01:32:37

回答

18

从Rails 3.1开始看起来像rjs已经removed as the default了。你可以通过安装prototype-rails gem来得到它,但我认为你应该只使用jQuery,这是新的默认值。

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

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

谢谢,我肯定会切换到jquery。 – 2012-04-16 03:36:55

6

在rails> = 3.1中没有jquery-rjs了。但是你可以使用CoffeeScript的位置: line_items/create.js.coffee

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

或类似的东西。