2011-04-21 61 views
3

我正在彈出模態框來提交表單。如果存在驗證問題,表單應該刷新,但仍在模態框內。這適用於添加新記錄,我相信這是調用:create操作,POST。我想使用相同的模式框來編輯記錄。到目前爲止,我可以在模式框中打開它,但只要出現錯誤,它就會重定向到另一個頁面,而不是留在框中。我認爲ajax並沒有調用這個動作來返回javascript來將表單放回模態框中。如何獲得ajax將JavaScript返回到模式框以更正表單?Rails如何通過Ajax調用返回javascript:更新控制器動作

例子,這裏是我的:創建行動:

def create 
@user = User.new(params[:user]) 

respond_to do |format| 
    if @user.save 
    format.js { render :redirect } #this is for modalform  
    format.html { redirect_to(users_url, :notice => 'User was successfully created.') } 
    else 
    format.html {render :new} 
    format.js # this renders the create.js.erb file to keep the form inside 
    end 
end 
end 

下面是加載模式對話框,並保持內部,直到驗證是否正確形式的javascript:

document.observe('dom:loaded', function() { 
$('newuser-link').observe('click', function(event) { 
    event.stop(); 
    Modalbox.show(this.href, 
     {title: 'Create', 
     width: 500, #up to this point, this opens the form in the modal box 
     afterLoad: function() { # this afterload part is supposed to keep the form inside the modal box 
      $('new_user').observe('submit', function(event) { 
       event.stop(); 
       this.request(); 
      }) 
     }} 
    ); 
    }); 
}) 

這裏是.js.erb文件:創建操作時調用如果存在驗證錯誤以將窗體保留在模式框內:

$('MB_content').update("<%= escape_javascript(render :partial => 'form') %>"); 
Modalbox.resizeToContent(); 
$('new_users').observe('submit', function(event) { 
event.stop(); 
this.request(); 
}); 

因爲這適用於:create動作,所以當我想編輯記錄時,如何使它適用於:update動作?再次,主要問題是,如果存在驗證錯誤,它將重定向到模態框之外。

UPDATE
我發現,是應該保持模式對話框打開的JavaScript的一部分:

$('new_user').observe('submit', function(event) { 
       event.stop(); 
       this.request(); 

的「new_user」是形式的ID。當使用此編輯記錄時,表單的編號爲edit_user_1或edit_user_32或正在編輯的任何用戶。所以我想這裏的解決方案,我不明白,是如何使用JavaScript中的類作爲選擇器而不是id。因爲當我手動輸入'edit_user_1'並且我正在編輯id爲1的用戶時,它可以工作......但顯然不適用於任何其他用戶。

回答

1

而不是使用ModalBox的最後我用FaceBox(教程這裏):

http://net.tutsplus.com/tutorials/ruby/how-to-build-an-unobtrusive-login-system-in-rails/

這幾乎是相同的,但似乎是在添加類或ID爲上更靈活選擇。此外,當它涉及到動態,生成的軌道ID的我用一點jQuery來創建一個變量,獲取動態鏈接並將其傳遞到選擇:

var myid = jQuery('#userform').children().attr('id'); 

然後,在它要求的id形式我通過在

'#' + myid 

無論如何,我得到這個按照上述的教程工作,甚至能夠修改與添加一個新用戶和編輯一個工作。

相關問題