Ruby on Rails Refactoring method example summary around MVC

The amount of code that increases and the readability that decreases when you write it as you want without thinking about it ... In order to summarize as concisely as possible, we have summarized the methods that can be used for each MVC for beginners.

Review the role of MVC

MVC role
Model Manipulation of data handled by the application/processing
View Displaying information to the user, receiving input from the user
Controller Exchange information with Model and View

Understand this role and describe the processing appropriate for each role. If you write in each file as you like without considering the role, maintenance will become difficult. For example, if the process to be described in Model is described in Controller, Fat Controller Problems such as (Controller with a lot of code written and swollen) are likely to occur.

How to reduce the amount of code in Controller

Describe in Model.

Considering each role of MVC mentioned above, the method responsible for data processing / processing is described in Model.

Before correction

app/controllers/posts_controller.rb


class PostsController < ApplicationController
  def index
    @posts = Post.order(created_at: :desc).limit(10)
  end
end

After correction (move to Model)

Defined as a class method so that it can be called directly to the Model class.

app/models/post.rb


class Post < ApplicationRecord
  def self.latest(number)
    order(created_at: :desc).limit(number)
  end
end

Call a method on the Controller

app/controllers/posts_controller.rb


class PostsController < ApplicationController
  def index
    @posts = Post.latest(10)
  end
end

You can also use scope instead of class methods.

app/models/post.rb


class Post < ApplicationRecord
  scope :latest, -> (number = 10){order(created_at: :desc).limit(number)}
end

app/controllers/posts_controller.rb


class PostsController < ApplicationController
  def index
    @posts = Post.latest
  end
end

How to reduce the amount of code in Model

Use Concern

When the same process is repeatedly described in multiple Models, Concern can be used to cut out the common process.

app/models/post.rb


scope :latest, -> (number = 10){order(created_at: :desc).limit(number)}
def hoge
  puts "hogehoge"
end

app/models/comment.rb


scope :latest, -> (number = 10){order(created_at: :desc).limit(number)}
def hoge
  puts "hogehoge"
end

Create a file in app / models / concerts and describe common processing.

app/models/concerns/common_module.rb


module CommonModule
  extend ActiveSupport::Concern
  included do
    scope :latest, -> (number = 10){order(created_at: :desc).limit(number)}
    def self.hoge
      puts "hogehoge"
    end
  end
end

Common processing can be used by including in each model.

app/models/post.rb


include CommonModule

app/models/comment.rb


include CommonModule

Cut out validation

The description of validation, which tends to be long, can be cut out to the validator. Create a validators directory under the app directory and create a file for validation.

app/validators/post_validator.rb


class PostValidator < ActiveModel::Validator
  def validate(record)
    prohibited_words = ["baka","aho"]
    if prohibited_words.any?{ |word| record.content.include?(word) }
      record.errors.add(:content, "Contains prohibited words.")
    end
  end
end

Describe additionally on the Model side.

app/models/post.rb


validates_with PostValidator

Cut out the callback

Callbacks can also be cut out from the Model. Create an app / callbacks directory and create a file for callbacks. (The class name should be the same as the callback name)

app/callbacks/post_callback.rb


class PostCallback
  def before_create(post)
    post.title = "No Title" if post.title.blank?
  end
end

Describe additionally on the Model side.

app/models/post.rb


before_create PostCallback.new

Recommended Posts

Ruby on Rails Refactoring method example summary around MVC
Ruby on Rails validation summary
Method summary to update multiple columns [Ruby on Rails]
Ruby on Rails variable, constant summary
[Ruby on Rails] Convenient helper method
Ruby on Rails installation method [Mac edition]
[Ruby on Rails] NoMethodError undefined method `devise_for'error resolution
Ruby on Rails ~ Basics of MVC and Router ~
Ruby on Rails address automatic input implementation method
Ruby on Rails Elementary
Ruby on Rails basics
Ruby On Rails Association
[Ruby] Method definition summary
[Ruby on Rails] Search function (model, method selection formula)
Ruby on rails learning record -2020.10.03
Portfolio creation Ruby on Rails
Ruby on rails learning record -2020.10.04
[Ruby on Rails] Debug (binding.pry)
Ruby on rails learning record -2020.10.09
Ruby on rails learning record-2020.10.07 ②
Ruby on rails learning record-2020.10.07 ①
Cancel Ruby on Rails migration
[Ruby] Notes on gets method
Ruby on rails learning record -2020.10.06
Ruby on Rails Basic Memorandum
[Ruby on Rails] undefined method ʻid'for nil: NilClass error resolution method
Ruby on Rails record search, create if not find_or_create_by method
[Ruby on Rails] Read try (: [],: key)
Installing Ruby + Rails on Ubuntu 18.04 (rbenv)
[Ruby on Rails] Introduced paging function
Basic knowledge of Ruby on Rails
Progate Ruby on Rails5 Looking Back
How to use Ruby on Rails
Ruby on Rails Japanese-English support i18n
(Ruby on Rails6) "Erase" posted content
[Ruby on Rails] CSV output function
Ruby on Rails 6.0 environment construction memo
[Ruby on Rails] Confirmation page creation
Ruby On Rails devise routing conflict
[Ruby on Rails] Comment function implementation
[Ruby on Rails] DM, chat function
[Ruby on Rails] Stop "looping until ..."
[Ruby on Rails] NoMethodError: undefined method `t'for # <ActiveRecord :: Migration: 〇〇〇〇> Dealing with errors
[Ruby on Rails] Follow function undefined method ʻid'for nil: NilClass error resolution
[Ruby on Rails] Introduction of initial data
[Ruby on Rails] Search function (not selected)
[Rails] Addition of Ruby On Rails comment function
[Ruby on Rails] Creating an inquiry form
Ruby on Rails6 Practical Guide cp13 ~ cp15 [Memo]
[Ruby on Rails] View test with RSpec
[Ruby on Rails] 1 model CRUD (Routing Main)
[Ruby on Rails] model, controller terminal command
Ruby on Rails model creation / deletion command
Ruby on Rails6 Practical Guide cp7 ~ cp9 [Memo]
Ruby on Rails in Visual Studio Codespaces
Notes on using FCM with Ruby on Rails
[Ruby on Rails] Controller test with RSpec
Deploy to Heroku [Ruby on Rails] Beginner
[Ruby on Rails] Image slideshow using Skippr
Preparing to introduce jQuery to Ruby on Rails
[Ruby on Rails] Japanese notation of errors