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..
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
$(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With