2012-04-13 35 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) %>' 

或類似的東西。