Below are the standard Rails 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).
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