2011-10-11 19 views
1

我有一個評論模型,我希望人們能夠保存草稿。它有一個布爾屬性「draft」,允許評論被保存(但還沒有出現)。我爲這些評論創建了自動保存功能。如何更改表單在jQuery自動保存提交中提交的操作? (在Rails中)

評論表格當前運行如下:變量@comment由控制器初始化爲@comment = Comment.new。那麼對於註釋的形式是:

<%= form_for @comment, :remote => true do |f| %> 
     <%= f.text_area :title, :class => "inputform" %> 
     <%= f.text_area :content, :class =>"inputform" %> 
     <%= f.submit "Submit", :class => "button" %> 
    <% end %> 

所以,我說,我想這是自動保存。要開始實現它,我寫了這個autosave_comments.js文件:

$(document).ready(function(){ 
     setInterval(function() { 
      $('new_comment .temp').html('<input type="hidden" name="comment[draft]" id="comment_draft" value="true" />'); 
      $('#comment_form form[data-remote]').submit(); 
      $('new_comment .temp').html(''); 
     }, 10000); 
    }); 

此代碼設置了草案的輸入是正確的,提交表單,然後刪除,對草案的輸入。這段代碼很好用,因爲它提交表單並將草稿保存到控制器。但是,每個提交都會保存一個新條目(即每隔10秒將新評論作爲草稿保存在數據庫中),而不是更新第一個條目。

背景的最後一點:當表單提交評論控制器,它提交給創建行動:

def create 
    @comment = params[:comment] 
    if @post.save 
     if params[:draft] 
       flash.now[:notice] = "draft autosaved" 
     else 
       flash.now[:success] = "comment created" 
     end 
    else 
     #code to output errors 
    end 
    respond_to do |format| 
      format.html 
      format.js 
    end 
    end 

這則引用create.js.erb文件:

<% post = user.posts.last %> 
    <% if post.draft == false %> 
     //code here deals with a true submission of a comment, to append tables etc. 
    <% else %> 
     //maybe some code here could alter the form on draft submission to make it update the same post next time? 
    <% end %> 

所以我想知道,我希望第一稿提交工作,因爲它和在註釋表創建一個條目。但是,我希望表單在隨後的自動保存中更新該評論,並在該人員提交發布評論時將該評論保存爲非草稿最終評論。在這些文件中有一處是我有概述說明我可以完成這個任務嗎?

謝謝!

回答

3

create.js.erb

$('#comment_form').attr('action', '<%= comment_path(@comment) %>'); 

只要確保您的評論的形式有comment_form的ID,或以其他方式相應地更改jQuery對象。其餘的應該由Rails來完成。

編輯我忘了你還需要像Rails那樣僞造PUT請求。由於一些瀏覽器不支持PUT請求,Rails使用POST,然後添加一個隱藏的表單字段:

<input name="_method" type="hidden" value="put" /> 

所以才產生在你create.js.erb

$('#comment_form').append('<input name="_method" type="hidden" value="put" />'); 
+0

這幾乎工作,但隨後在POST到localhost,它運行一個無路由錯誤:ActionController :: RoutingError(沒有路由匹配「/ posts/139」)。我不知道它爲什麼這樣做,對我來說它應該與你寫的代碼一起工作。有任何想法嗎? – geb2011

+0

我的錯誤,請參閱我的編輯。 – bricker

+0

是的,它修復了它!謝謝 – geb2011