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..
- Auto-save periodically (1 min intervals, perhaps)
- Give option to save draft
- 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!
Auto-save:
application.js
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 thePostDraft
object, and then once they click "Publish" or whatever, it will create a newPost
and delete thePostDraft
. 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 thePost
model with a "draft" boolean.