what's a RESTful way to save draft posts?

2019-03-11 11:29发布

I have a posts controller on a small test website I'm making. I want to have a 'save draft'/combo-auto-save function to the site, as the site will have long posts that users may want to leave and come back to finish. However, I've never built an autosave/save function into a Rails app before (or any app). What is a good, RESTful way to do so?

Here is my current controller action:

posts_controller.rb

 def create

 @post = params[:post]
 if @post.save
     flash.now[:success] = "Post created!"
 else 
     render_errors_now(@post) 
 end
     respond_to do |format|
           format.html {redirect_to Discussion.find(session[:discussion_id])}
           format.js
     end
 end

As you can see, users post remotely.

Here is the current post.rb model:

 attr_accessible :content, :title
 validates :title, :presence => true 
 validate :title_character_length

 validates :content, :length => { :maximum => 10000 }
 validates :user_id, :presence => true
 validates :discussion_id, :presence => true
 belongs_to :user
 belongs_to :discussion
 default_scope :order => 'posts.created_at ASC'

 def title_character_length
    #some code that checks length
 end

I would need to accomplish the following things from this code..

  1. Auto-save periodically (1 min intervals, perhaps)
  2. Give option to save draft
  3. Choose which validations to run: I would want to allow users to, for example, save a draft with a title that exceeds the allowed length, while not allowing them to actually post a post with that title.

I also am curious what is a good Rails practice for saving drafts: should I add an attribute "draft" to the post model? Or create a draft posts model?

OK please comment if I need to provide more info. I'm interested to hear people's input! Thanks everyone!

1条回答
成全新的幸福
2楼-- · 2019-03-11 11:50

Auto-save:

application.js

$(document).ready(function() {
  setInterval(function() {
    $('form[data-remote]').submit();
  }, 1000*60); // 1000ms * 60s = 1m
});

You'll then need to have an update.js.erb to handle the messages ("Saved", for example).

For drafts, I would make a separate model, PostDraft. The auto-save will be saving the PostDraft object, and then once they click "Publish" or whatever, it will create a new Post and delete the PostDraft. This method will also allow the user to have titles longer than the limit, just by not putting that validation on the PostDraft model. This would be a lot more difficult if you did it all from within the Post model with a "draft" boolean.

查看更多
登录 后发表回答