[Ruby] [Rails] Created draft function using enum

1 minute read

Introduction

There weren’t many articles when I thought about making a draft function, so I decided to keep it as a record.

Development environment

ubuntu (WSL)
Ruby 2,5.1
Rails 6.0.2

Advance preparation

The following functions have been created.

  • Post function/Details/Delete/Edit (Post)
  • User creation/details (User)

models/post.rb


  belongs_to :user

models/user.rb


  has_many :microposts, dependent: :destroy

Add columns to the Post table

First, add a status column to the Post model and make it a boolean type. You can use interger instead of boolean. Enter the following command.

bin/rails g migration AddStatusToPost status:boolean

Edit the migration file.

migrationfile.rb


  def change
    add_column :microposts, :status, :boolean, default: true, null: false
  end

Migrate after editing.

Add enum to Post model.

models/post.rb


  enum status: {draft: false, published: true}

Specify draft (draft) of status column as false, and publish (publish) of status column as true

Get information for each user

Get user’s id with @user.

users_controller.rb


  #For draft
  def confirm
    @user = User.find(params[:user_id])
    @microposts = @user.microposts.draft.page(params[:page])
  end

  #For public
  def show
    @user = User.find(params[:id])
    @microposts = @user.microposts.published.page(params[:page])
  end

add routing

If you add collection, the id will not be added to the URL

routes.rb


resources :users do
  get'confirm'
end

View settings

I have extracted only relevant parts.

view/users/show.html.slim


// User details screen
= link_to "Post list", @user
= link_to "Favorites", user_likes_path(current_user)
= link_to "Draft list", user_confirm_path(current_user)

// view your post
- if @microposts.present?
  = render "microposts/list", microposts: @microposts
- else
  h4 no posts

Please write the draft list according to your preference.

view/users/confirm.html.slim


h4 draft list

table.table.table-hover
  thead.thead-default
    tr
      th = Micropost.human_attribute_name(:title)
      th = Micropost.human_attribute_name(:content)
      th = Micropost.human_attribute_name(:created_at)
      th
  tbody
    [email protected] do |micropost|
      tr
        td = link_to micropost.title, micropost
        td = link_to micropost.content, micropost
        td

The contents of icroposts/list are the same as above.

At the end

If you make a mistake, please make an edit request and comment.

References