2014-07-11 10 views
1

所以我最初在我的rails應用程序中實現ajax的方式是爲每個控制器的每個動作創建一個js文件,然後在respond_to中引用該js文件塊。從控制器返回javascript而不採取行動特定的js文件

這真的很煩人,我喜歡將所有的javascript包含在一個main.js文件中,而不是對每個片段進行劃分。

到目前爲止,這一直很好地工作,除了當我想傳遞一個對象到適當的功能。

這是我應該如何處理Ajax請求在我的應用程序創建一個新的用戶列表:

<%= form_for @client, action: :create, remote: true do |f| %> 
    <%= f.text_field :firstname, placeholder: 'First Name' %> 
    <%= f.text_field :lastname, placeholder: 'Last Name' %> 
    <%= f.hidden_field :status, value: true %> 
    <%= submit_tag :create %> 
<% end %> 

....形式獲取遠程:真正的標籤。

def create 
    @client = current_trainer.clients.create(client_params) 
    respond_to do |format| 
    format.html { redirect_to clients_path } 
    format.js 
    end 
end 

....創建行動響應傳遞到默認創建的文件:

$('.active').prepend("<%= j render @client %>"); 

這是所有罰款和花花公子。但我不喜歡這種設置。我要讓這樣的,而不是一個電話:

def create 
    @client = current_trainer.clients.create(client_params) 
    respond_to do |format| 
    format.html { redirect_to clients_path } 
    format.js { render js: "theApp.clientsPage.saveClient();" } 
    end 
end   

....然後在main.js.erb文件我有:

saveClient: function() { 
     $('.active').prepend("<%= j render @client %>"); 
    }, 

,但我得到的錯誤是以下:

undefined method `render' for #<#<Class:0x007fd278f350c8>:0x007fd27b182298> 

回答

0

main.js.erb只包括佈局我認爲,是嗎?然後它會在發佈時進行編譯(例如您的main#index操作中的此表單)index操作,並且您沒有@client

只要給一個參數saveClient功能,像這樣:

saveClient: function(newElement) { 
    $(".active").prepend(newElement); 
}, 

然後在create行動呼籲:

format.js { render js: "theApp.clientsPage.saveClient($(\"<div>#{ j render @client }</div>\"));" } 
+0

這更接近我的看法,但沒有雪茄。它從字面上追加文本'<%= j render @client%>'而不是應該評估的代碼。 –

+0

@ ninja08當然,對不起。當然必須是「#{...}」。更好的追加一些塊而不是文本,例如'div'。 – ostapische

+0

謝謝,雖然這不起作用。 –

相關問題