[RUBY] About Rails controller

Overview

I would like to explain about the ** controller ** of Rails application.

This goal

** "Knowing about MVC model" ** ・ ** "About the role of controller" ** ・ ** "Practical usage" **

1. What is an MVC model?

This is one of the ideas for managing code well when creating an application. It's just one way of thinking, so it's not absolutely correct. Rails applications incorporate this MVC framework.

3 elements of MVC

** "Model" ** ・ ** "View" ** ・ ** "Controller" **.   ・ Model ・ ・ ・ Responsible for business logic in the system

View ・ ・ ・ Processing such as display and input / output

Controller ・ ・ ・ Controls Model and View based on user input

MVC processing flow in Rails

  1. ** "Controller" ** receives a request from a client

  2. For ** "Controller" **, ask ** "Model" ** for data processing.

  3. ** "Model" ** processes data from the database and returns the data to ** "Controller" **

  4. ** "Controller" ** asks you to process the data received in ** "View" **

  5. ** "View" ** creates a form (HTML document) suitable for the client to see and returns it to ** "Controller" **

  6. ** "Controller" ** returns the HTML text to the client as a response

By repeating 1 to 6, it is established as a Web application.

2. About the role of the controller

** Conclusion ** -Execute the ** action method ** of the specified controller based on the information sent from the routing. ・ ** Link with Model / View ** to return a response to the client

Action method

This method describes the specific processing content of the action specified from the routing.

Image of action method


class SamplesController < ApplicationController
  def index
    #Specific processing content
    ......
    ......
  end
end

In this example ... When the index action of the samples controller is specified in the routing, describe the action method to be executed in the form of def index ... end.

About cooperation with Model

Purpose

Creating, modifying, or retrieving a database through a model.

Method

Instruct the model using the methods of the ActiveRecord class that the model inherits. Below are some examples of methods.

Method Contents
all Get all the data in the database
find Get one piece of data in the database
new Generate new data creation
save Save data in database

Method image


  (Model class name).[Method]
  Sample.all

About cooperation with View

Purpose

Passing the data received from the model to the view and creating the response data to return to the client.

Method

Assign instance variables to the data from the model.

  @samples = Sample.all

This makes the data available in the view file.

3. Practical usage

Controller setting location

In the ʻapp / controllersdirectory Set thecontroller name_controller.rb` file.

Controller naming convention

Basically ** "plural" **. The reason is that it automatically guesses the files used by Rails by name. It could be singular, but the developer would have to explicitly write the code and it would cause an unexpected error.

name Example Remarks
Controller name samples
Controller class name SamplesController Camel case
Controller file name samples_controller.rb Snake case

Controller file structure

The contents of the controller file look like this.

app/controllers/samples_controller.rb


  class SamplesController < ApplicationController
    def index
      #Specific processing content
      ......
      ......
    end
  end

The created controller file inherits ** "ApplicationController class" **.

What is the ApplicationController class?

app/controllers/application_controller.rb


  class ApplicationController < ActionController::Base
  end

ʻThe class defined in the app / controllers / application_controller.rb` file. It's a (almost) empty class that just inherits from the ** ActionController :: Base class **.

In principle, each controller inherits from the ApplicationController class It is used when common application functions (login / logout, etc.) are required.

What is the ActionController :: Base class?

A class that provides the basic functionality of the controller. It is responsible for the basic part related to request / response processing.

Handling HTTP request parameters

The controller gets the parameters of the HTTP request from the client via ** "params method" **.

params method

Rails implicitly processes ** request parameters ** and stores the data in params in hash format. There is no difference in how data is received even when accessed by ** GET request / POST request **.

Access by GET request

Access the web server by including the parameter in ** "Request URI" ** of the request line of the HTTP request. You can pass parameters in ** "URL format" ** and ** "query format" **.

URL format

When the following routing settings are made

  Prefix Verb   URI Pattern               Controller#Action
  user   GET    /users/:id(.:format)      users#show

If you access with the URL http://sample.com/users/7 The : id parameter of the request means 7 In Rails, it is stored in params and the value of params [: id] is " 7 ".

app/controllers/users_controller.rb


  class UsersController < ApplicationController
    def show
      params[:id] # "7"
    end
  end

Query format

At the end of the URL, write "?" Followed by "parameter name = value". If there are multiple parameters, connect them with "&" and describe them.   Using the same routing in the example above When you access with the URL http://sample.com/users/7?keyword=query&num=10 The value of params [: keyword] is " query ", and params [: num] is " 10 ".

app/controllers/users_controller.rb


  class UsersController < ApplicationController
    def show
      params[:keyword] # "query"
      params[:num] # "10"
    end
  end

Access by POST request

This is a request that occurs when the client presses the "Submit" button when inputting from the form. Access the web server by including the parameters in the ** "body" ** of the HTTP request.

You can also send more parameters than a GET request.

Precautions when saving params

When saving "params" in the database, use a mechanism called ** "Strong Parameters" **.

What is Strong Parameters?

It is a mechanism to eliminate the vulnerability of "Mass Assignment" that was used up to Rails3 series. In "Mass Assignment", params information about saving was described in ** model **. In "Strong Parameters", describe the information of params to be saved in ** controller **.

Strong_Image of Parameters


  class UsersController < ApplicationController
    def create
      @user = User.new(user_params) # user_Create new data using params method
      @user.save #Save to database via model
    end

    #Strong Parameters are not called from outside the class, so write them in a private method.
    private
    def user_params
      params.require(:user).permit(:name, :age)
    end
  end

In this example In the ʻuser_params method, the parameters to be saved are specified in: nameand: age of: user`.

require method

Specify the table name to be saved in the database.

permit method

Specify the column name to be saved in the database table.


That is all for the explanation of the controller. Thank you very much.

Recommended Posts

About Rails controller
About Rails 6
About Rails routing
[Rails] About ActiveJob ,!
About RSpec (Rails)
[Rails] About migration files
[Rails 6] About main gems
[Rails] About active hash
About rails application server
About rails kaminari pagination
About rails version specification
MEMO about Rails 6 series
[Rails] About Slim notation
Rails: About partial templates
About rails strong parameters
[Beginner] About Rails Session
Get UserAgent in [Rails] controller
[Ruby on Rails] about has_secure_password
About naming Rails model methods
[Rails] About scss folder structure
About =
[Rails] About Rspec response test
Rails routing controller view relationship
About Rails scraping method Mechanize
[Rails] About the Punk List function
About the symbol <%%> in Rails erb
[Rails] About helper method form_with [Basic]
Consideration about Rails and Clean Architecture
About method.invoke
[Rails g.error]
About Kotlin
About attr_accessor
Rails basics
Rails Review 1
Rails API
Rails migration
About inheritance
About params
About Docker
Rails: 7 basic actions defined on the controller
rails tutorial
[Ruby on Rails] model, controller terminal command
About form_for
About Spring ③
[Ruby on Rails] About bundler (for beginners)
About enum
[rails] List of actions defined in Controller
[Rails 6.0] About batch saving of multiple records
Rails foundation
About polymorphism
About Optional
Rails memorandum
About hashes
About JitPack
[Rails] Use validation on a specific controller
rails tutorial
About Dockerfile
rails tutorial
rails tutorial
[Ruby on Rails] Controller test with RSpec
About this ()