【问题标题】:How can I change the action a form submits to in a jQuery autosave submission? (In Rails)如何在 jQuery 自动保存提交中更改表单提交的操作? (在 Rails 中)
【发布时间】:2011-10-11 14:45:09
【问题描述】:

我有一个评论模型,我希望人们能够为其保存草稿。它有一个布尔属性“draft”,允许保存评论(但尚未显示)。我正在为这些 cmets 创建一个自动保存功能。

当前的评论表单运行如下:变量@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_cmets.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 秒就有一个新评论作为草稿保存在数据库中),而不是更新第一个条目。

最后一点背景:当表单提交给 cmets 控制器时,它提交给 create 动作:

 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 %>

所以我想知道,我希望提交的初稿能够正常工作,并在评论表中创建一个条目。但是,我希望表单在后续自动保存时更新该评论,并在该人提交评论以供发布时将该评论保存为非草稿最终评论。这些文件中的某个地方是否有我可以完成此任务的概述?

谢谢!

【问题讨论】:

    标签: jquery ruby-on-rails ruby-on-rails-3 autosave


    【解决方案1】:

    create.js.erb:

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

    只需确保您的评论表单的 ID 为 comment_form,或者相应地更改 jQuery 对象。 Rails 应该负责其余的工作。

    edit 我忘了你还需要像 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" />');
    

    【讨论】:

    • 这几乎可以工作,但是在 POST 到 localhost 时,它运行一个无路由错误:ActionController::RoutingError(没有路由匹配“/posts/139”)。我不知道它为什么这样做,对我来说它应该与您编写的代码一起使用。有什么想法吗?
    猜你喜欢
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 1970-01-01
    • 2013-03-15
    相关资源
    最近更新 更多