Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Good way to support creation of drafts for several models

I want to allow users to create drafts of several models (such as article, blog post etc). I am thinking of implementing this by creating a draft model for each of my current models (such as articleDraft, blogpostDraft etc.). Is there a better way to do this? Creating a new model for every existing model that should support drafts seems messy and is a lot of work.

like image 891
Matthew Hui Avatar asked Nov 01 '25 06:11

Matthew Hui


2 Answers

I think the better was is to have a flag in the table (ex: int column called draft), to identify if the record is a draft or not.

Advantages of having such a column with out a separate table, as I can see:

  1. It's easy to make your record non-draft (just change the flag)

  2. you will not duplicate data (because practically you will have the same in draft and non-draft records)

  3. coding will be easy, no complex login

  4. all the data will be in one place and hence less room for error

like image 105
sameera207 Avatar answered Nov 02 '25 20:11

sameera207


I've been working on Draftsman, a Ruby gem for creating a draft state of your ActiveRecord data.

Draftsman's default approach is to store draft data for all drafted models in a single drafts table via a polymorphic relationship. It stores the object state as JSON in an object column and optionally stores JSON data representing changes in an object_changes column.

Draftsman allows for you to create a separate draft model for each model (e.g., article_drafts, blog_post_drafts) if you want. I agree that this approach is fairly cumbersome and error-prone.

The real advantage to splitting the draft data out into separate models (or to just use a boolean draft flag on the main table, per sameera207's answer) is that you don't end up with a gigantic drafts table with tons of records. I'd offer that that only becomes a real problem when your application has a ton of usage though.

All that to say that my ultimate recommendation is to store all of your draft data in the main model (blog) or a single drafts table, then separate out as needed if your application needs to scale up.

like image 41
Chris Peters Avatar answered Nov 02 '25 19:11

Chris Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!