Definitions other than 7 basic actions in Rails

Review of basic actions

Below are the standard Rails actions スクリーンショット 2020-05-16 15.12.28.png

Define your own actions

If you want to perform processing other than the above basic actions, you can define it yourself.

** collection ** and ** member ** can be used to define the routing at that time.


Rails.application.routes.draw do
  resources :hoges do
    collection do
HTTP method'Original method name'
    end
  end
end
Rails.application.routes.draw do
  resources :hoges do
    member do
HTTP method'Original method name'
    end
  end
end

The difference is whether the generated routing has ** id ** or not.

・ Collection →: No id ・ Member →: with id

If you need to move to a specific page, it's like using member.

And the important thing is where to write the content of the method.

In general, even at the development site, it seems that it is customary to describe the method related to the interaction with the table (DB) in the model.

For example, when you want to implement a search function, write a method to perform that process in the model and call it with the controller (the description of the view search form etc. is omitted).

Example of use

routes.rb


 resources :tweets do
    collection do
      get 'search'
    end
  end

tweet.rb


class Tweet < ApplicationRecord
  #abridgement

  def self.search(search)
    return Tweet.all unless search
    Tweet.where('text LIKE(?)', "%#{search}%")
  end
end

tweets_controller.rb


class TweetsController < ApplicationController
 
  #abridgement
  

  def search
    @tweets = Tweet.search(params[:keyword])
  end

end

To explain each,

First, set up the routing for the search action. I don't have to go to the details page to see the search results, so I'm using collection.

When the user searches on the form, the controller calls the search method described in the model from the search action. At that time, the search result is passed as an argument (params [: keyword])

The search result is assigned to the variable search in the model's search method and can be used in the method.

If the content of search is empty, all posts will be fetched, and if there is a value, posts that match the conditional expression in the content of where method will be fetched.

Recommended Posts

Definitions other than 7 basic actions in Rails
Set Rails routing other than id
Rails: 7 basic actions defined on the controller
[rails] List of actions defined in Controller
(Basic authentication) environment variables in rails and Docker
Group_by in Rails
Rails basic philosophy
Model association in Rails
Adding columns in Rails
Disable turbolinks in Rails
CSRF measures in Rails
^, $ in Rails regular expression
Use images in Rails
Understand migration in rails
Split routes.rb in Rails6
Implement markdown in Rails
Use Rails template function (ERB) other than Controller (Action View)