开发者

Best way to create preview functionality in Rails

开发者 https://www.devze.com 2022-12-31 22:59 出处:网络
I\'m looking to implement preview functionality in my posts scaffold. All I need to do is allow a user to enter information in the new view (/posts/new) and then replace the submit button with a previ

I'm looking to implement preview functionality in my posts scaffold. All I need to do is allow a user to enter information in the new view (/posts/new) and then replace the submit button with a preview button.

Once the preview button is clicked, the user is routed to the preview page (probably /posts/new/preview). If the user wants to make a change they would click 'go back' or if they 开发者_如何学JAVAare happy with the post they can then submit the post.

I found this article (http://eyedeal.team88.org/node/105) but it seems dated. Any ideas on what the best approach for this would be?

Many thanks, Tony


On submit from create page, in the new action, build the object but do not save it to the database. Then render the object in its show view with a flag set in the new action to display a submit button. In your show view, always have a form with all the attributes of the object to be saved to db in hidden input fields or in display:none's. When the flag is set, you show the submit button. On submit, you go to the new_to_db action which saves the object to the db.


The link you have posted is a way, but I prefer to save object and set a boolean flag, let's say public to false (:default => false defined in migration). Then what you basically do is actually create the post and redirect to show action, where you have edit button (render edit action), post button (custom action to set public flag to true) and cancel button (which actually deletes the post) and maybe continue later button, which keeps the post and redirects to any other page, so the user can come back later and finish editing it.

When you need to show all posts, define a named_scope :visible, :conditions => ['posts.public = ?', true] and call Post.visible instead of Post.all in index and similar actions. You could also define a default_scope with conditions ['posts.public = ?', false], but bare in mind that if you want to find posts that are not visible, you will have to use #without_scope.

This way is better than the one in your link, because user can always come back later and finish editing the post and the publish it. However you will store more objects in DB and have to deal with invisible posts (don't show them by default, etc.)

0

精彩评论

暂无评论...
验证码 换一张
取 消