[Ruby] [Rails] A simple way to implement a self-introduction feature in your profile

1 minute read

Implement self-introduction function in profile

After the portfolio is completed, since it is implemented additionally, the order is left as a memorandum. Add a new introduction column to the existing columns such as user name, email and password. I will write as simple as possible!

how?

The order is as follows.

  1. git checkout -b introduction (branch off)
  2. Add introduction column to users table
  3. Reflect in database
  4. Add required code to users controller
  5. Add required code to user model
  6. Display on the user details page (MYPAGE)
  7. Display on the user edit page (EDIT)
  8. Complete!

I will write them in order below!

1. git checkout -b introduction (branch off)

Break the branch to implement new functionality.

2. Add introduction column to users table

terminal


$ rails generate migration AddIntroductionToUsers introduction:text
      invoke active_record
      create db/migrate/20200712005652_add_introduction_to_users.rb

Add the introduction column with the rails g command above.

3. Apply to database

terminal


$ docker-compose run web rails db:migrate
== 2020~~~~ AddIntroductionToUsers: migrating ============================
- -add_column(:users, :introduction, :text)
   -> 0.0518s
== 2020~~~~ AddIntroductionToUsers: migrated (0.0519s) ==================

4. Add required code to users controller

Add to private method Add introduction attribute

users_controller.rb


   def user_params_update
      params.require(:user).permit(:name, :email, :image, :introduction) # added introdution
   end

Now you can update the introduction

5. Add required code to user model

Add validation. You can enter the self-introduction within 50 characters. Please set the number of characters freely.

  • Although it is presense, please be aware that if you do not set it to false, it will act when you register and new information will be nil and you will not be able to register again. If you need to enter self-introduction when you register for new, true is OK.

user.rb


validates :introduction, presence: false, length: {maximum: 50} # Maximum of 50 characters for self-introduction

6. Display on the user details page (MYPAGE)

ruby:show.html.slim


 = @user.introduction

Please correct it with SCSS etc.

7. Display on user edit page (EDIT)

User edit was only user name and email, but I will add introduction there.

ruby:edit.html.slim


.form-group
  = f.label :introduction
  = f.text_area :introduction, class:'form-control', id:'user_introduction'

Complete

With the above, we have added self-introduction to the users table and added the introduction attribute. Please note that the introduction was written as “introduce” along the way!

Screenshot 2020-07-12 13.33.19.png