什么是保存草稿帖子的 RESTful 方式? [英] what's a RESTful way to save draft posts?
问题描述
我正在制作的一个小型测试网站上有一个帖子控制器.我想为网站提供保存草稿"/组合自动保存功能,因为该网站将有很长的帖子,用户可能想要离开并回来完成.但是,我之前从未在 Rails 应用程序(或任何应用程序)中构建过自动保存/保存功能.什么是 RESTful 的好方法?
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
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.
这是当前的 post.rb 模型:
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 分钟)
- 提供保存草稿的选项
- 选择要运行的验证:例如,我希望允许用户保存标题超过允许长度的草稿,但不允许他们实际发布具有该标题的帖子.
我也很好奇 Rails 保存草稿的良好做法是什么:我应该向后期模型添加属性草稿"吗?或者创建一个草稿帖子模型?
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!
推荐答案
自动保存:
application.js
$(document).ready(function() {
setInterval(function() {
$('form[data-remote]').submit();
}, 1000*60); // 1000ms * 60s = 1m
});
然后您需要有一个 update.js.erb
来处理消息(例如已保存").
You'll then need to have an update.js.erb
to handle the messages ("Saved", for example).
对于草稿,我会制作一个单独的模型,PostDraft
.自动保存将保存 PostDraft
对象,然后一旦他们单击发布"或其他任何内容,它将创建一个新的 Post
并删除 PostDraft代码>.此方法还将允许用户拥有超过限制的标题,只需不要将该验证放在 PostDraft 模型上.如果您在带有草稿"布尔值的
Post
模型中完成所有操作,这将变得更加困难.
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.
这篇关于什么是保存草稿帖子的 RESTful 方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!