[Rails] Implementation procedure when public / private functions are added to the posting function

Introduction

We have added the function of publishing / private articles to the portfolio we are creating, so we will introduce the implementation procedure. I posted an article, but I think there are times when I want to keep it private, so I implemented it.

Premise

--Using the gem function of kaminari, I get a list of private articles --Using devise's gem feature to redirect other users from private articles

version information

Implemented procedure

Added status column to posts table

$ rails g migration Add_status_To_posts status:integur

db/migrate/20201111213454_add_status_to_posts.rb


class AddStatusToPosts < ActiveRecord::Migration[6.0]
  def change
    add_column :posts, :status, :integer, null: false, default: 0
  end
end

Define model

app/models/post.rb


class Post < ApplicationRecord

#···abridgement

  enum status: { public: 0, private: 1 }, _prefix: true

#···abridgement

end

When I opened the browser without writing _prefix: true as above, I got the following error. Checking the error statement, it is said that the method `public``` is duplicated. If there are no duplicate errors, you do not need to write `_prefix: true```.

log/development.log


ArgumentError (You tried to define an enum named "status" on the model "Post", but this will generate a class method "public", which is already defined by Active Record.):
  
app/models/post.rb:19:in `<class:Post>'
app/models/post.rb:1:in `<main>'
app/controllers/posts_controller.rb:85:in `set_post'
Started GET "/posts/3" for 127.0.0.1 at 2020-11-12 06:52:36 +0900
Cannot render console from 172.22.0.1! Allowed networks: 127.0.0.0/127.255.255.255, ::1
   (1.2ms)  SET NAMES utf8mb4,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
Processing by PostsController#show as HTML
  Parameters: {"id"=>"3"}
Completed 500 Internal Server Error in 27ms (ActiveRecord: 0.0ms | Allocations: 5566)

Allows you to select post status on the post edit page

erb:app/views/posts/_form.html.erb


<%= form_with(model: post, local: true) do |form| %>

<!--···abridgement···-->

  <%= form.label(:public, for: nil, class:'post-status__label') do %>
      <%= form.radio_button :status, :public %>
      <%= I18n.t('activerecord.attributes.post.statuses.public') %>
  <% end %>
  <%= form.label(:private, for: nil, class:'post-status__label') do %>
      <%= form.radio_button :status, :private %>
      <%= I18n.t('activerecord.attributes.post.statuses.private') %>
  <% end %>

<!--···abridgement···-->

<% end %>

The UI for selecting public / private is as follows. The implementation procedure is not the main topic in this article, so I will omit it. However, this implementation took a long time.

post_status.gif

Allows you to save selected post status

app/controllers/posts_controller.rb


class PostsController < ApplicationController

#···abridgement

  def create
    @post = Post.new(post_params)
    @post.user_id = current_user.id

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'I made a new post.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

#···abridgement

  private

#···abridgement

    def post_params
      params.require(:post).permit(
        :title,
        :content,
        :image,
        :status, # <=Added: status column
        {:cat_ids => []}
      )
    end

#···abridgement

end


Private article list and detail page are redirected when accessed by other users

app/controllers/posts_controller.rb


class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts/1
  # GET /posts/1.json
  def show

    if @post.status_private? && @post.user != current_user
      respond_to do |format|
        format.html { redirect_to posts_path, notice: 'This page cannot be accessed' }
      end
    end

    #···abridgement
  end

  #···abridgement

  private
    def set_post
      @post = Post.find(params[:id])
    end

    #···abridgement

end


How to get the article list

#Public article
$ Post.status_public.order(created_at: :desc).page(params[:page])

#Private article
$ Post.status_private.order(created_at: :desc).page(params[:page])

#Ranking(Top 3 of Like)
$ Post.status_public.joins(:likes).group(:post_id).order('count(likes.post_id) desc').limit(3)


Time required

Work content Time required
Estimates 0.75H
Implementation / Verification: New post 7H
Implementation / Verification: User detail page 2.25H
Implementation / verification: Post details page(localhost/posts/:id) 1H
Implementation / Verification: Article list / detail page(Like Ranking) 0.5H
Implementation / Verification: Article List(localhost/posts) 0.125H
Implementation / Verification: TOP(localhost) 0.125H
total 12H

It took me 7 hours to make the post edit page, so I regret it, but I'm glad I managed to make it.

finally

We hope that this article will be helpful when adding public / private functions to the article.

reference

[Rails] enum tutorial Use _prefix _suffix when using enum from Rails5

Recommended Posts

[Rails] Implementation procedure when public / private functions are added to the posting function
[Rails] The 12 functions that beginners have added to the problem-solving portfolio are these!
[Rails] Comment function implementation procedure memo
[Rails] I will explain the implementation procedure of the follow function using form_with.
Strict_loading function to suppress the occurrence of N + 1 problem added from rails 6.1
Rails Basic CRUD function implementation procedure scaffold
[Rails] Implementation procedure of the function to tag posts without gem + the function to narrow down and display posts by tags
[Rails6] How to connect the posting function generated by Scaffold with the user function generated by devise
[Ruby on Rails] Implementation of validation that works only when the conditions are met
[rails] gem'payjp' implementation procedure
Rails search function implementation
When a beginner makes a personal app with rails, the procedure to bring it to the starting point anyway.