Tag: Rails/Ajax
<div class="blog-form"> <%= form_for(@post) do |f| %> <%= f.text_field :tilte %> <%= f.text_area :body %> <!-- for temporal saving --> <div class="create-temp"></div> <%= f.submit "送信する" %> <% end %> </div>
var ready, tempSubmit; ready = function() { if ($('.create-temp')) { window.tempTimer = null; return $('.blog-form form').keydown(function() { window.clearTimeout(tempTimer); return window.tempTimer = window.setTimeout(function() { return tempSubmit(); }, 5000); }); } }; tempSubmit = function() { if ($('.create-temp span').data('result') !== true) { return $(".blog-form form").ajaxSubmit({ url: '/posts/temp', type: 'post' }); } else { return $(".blog-form form").ajaxSubmit(); } }; $(document).ready(ready); $(document).on('page:load', ready);
post '/posts/temp', to: 'posts#create_temp', as: :temp_post
def create @post = Post.new(post_params) if @post.save redirect_to(@post) else render('new') end def create_temp @post = Post.new(post_params) @post.save end def update respond_to do |format| if @post.update(post_params) format.js {} format.html {redirect_to @post, notice: 'Post was successfully updated.'} else format.js {} format.html {render :edit} end end end
var result = <%= @post.valid? %>; var msg = ""; var notice = ""; if (result == true) { msg = "下書き保存されました"; // This is for Temporal saving // forcing the form to look update method. // Add id $('.blog-form form').prepend('<input name="post[id]" type="hidden" value="<%= @post.id %>">'); // Chnage REST method $('.blog-form input[name=_method]').remove(); $('.blog-form form').prepend('<input name="_method" type="hidden" value="patch">'); // Change URL $('.blog-form form').attr('action', '/posts/<%= @post.id %>'); } else { msg = "下書き保存のための情報が足りません"; } // Message notice = "<span data-result=" + result + ">" + msg + "</span>"; $('.create-temp span').remove(); $('.create-temp').hide().append(notice).fadeIn();
var persisted = <%= @post.persisted? %>; var result = <%= @post.valid? %>; var msg = ""; if (result == true) { msg = "下書きが更新保存されました"; } else { msg = "下書き更新保存のための情報が足りません"; } // Message notice = "<span data-result=" + persisted + ">" + msg + "</span>"; $('.create-temp span').remove(); $('.create-temp').hide().append(notice).fadeIn();
after_filter :clear_flash private def clear_flash flash.discard if request.xhr? end
def update respond_to do |format| if @post.update(post_params) format.js {} format.html {redirect_to @post, notice: 'Post was successfully updated.'} else format.js {} format.html {render :edit} end end end