Action Draft
Action Draft brings your ActiveRecord model to storage multiple draft attributes without add columns to the business table.
Features
- Save drafts without add columns to the business table.
- Work any ActiveRecord model, just add
has_draft :field_name. - A
publishmethod for assignment the draft values to actual attributes. - Fallback to actual attribute value when draft is nil.
Installation
gem "action-draft"
And then execute:
$ bundle
$ rails action_draft:install
Usage
In your ActiveRecord model:
# app/models/message.rb
class Message < ApplicationRecord
has_draft :title, :content
end
Now you have draft_title, draft_content attributes.
Then refer to this field in the form for the model:
<%# app/views/messages/_form.html.erb %>
<%= form_with(model: message) do |form| %>
…
<div class="field">
<%= form.label :draft_title %>
<%= form.textarea :draft_title %>
</div>
<div class="field">
<%= form.label :draft_content %>
<%= form.textarea :draft_content %>
</div>
…
<% end %>
Save draft attributes:
irb> message = Message.new
irb> message.draft_title = "Draft title"
irb> message.draft_title.to_s
"Draft title"
irb> message.draft_content = "Draft message content"
irb> message.draft_content.to_s
"Draft message content"
irb> message.save
ir> message.reload
irb> message.draft_title.to_s
"Draft title"
irb> message.draft_content.to_s
"Draft message content"
Publish draft content:
irb> message = Message.new
irb> message.draft_title = "Message title"
irb> message.publish
irb> message.new_record?
false
irb> message.title
"Message title"
irb> message.draft_title
"Message title"
License
The gem is available as open source under the terms of the MIT License.