Currently, I am attending a certain programming school, but when implementing the search function (search window), I was told to use a model and a controller for processing properly. Eh ... It's okay to use all the controllers ... (Of course, I'm actively using them separately now!)
** ・ Controller… Data is acquired from DB, saved, and only simple processing is described ** ** ・ Model: Describes the value obtained from the DB that performs complicated processing ** I use it properly with the image.
However, I didn't want to use it because I couldn't understand why the ** "processing catalog" ** set in the model could be used with the controller, no, I couldn't. (This article is not an article to explain the search function. It is just a summary of my mind about how to use the model.)
models/tweet.rb (model)
class Tweet < ApplicationRecord
validates :text, presence: true
belongs_to :user
has_many :comments
def self.search(search)
return Tweet.all unless search
Tweet.where('text LIKE(?)', "%#{search}%")
end
end
controllers/tweets_controller.rb (controller)
class TweetsController < ApplicationController
def search
@tweets = Tweet.search(params[:keyword])
end
end
It's not listed in the reference. Because ** "method made by model" **! !!
――I won't explain in detail here, but ** class name is assigned ** to this one. (The expression assignment is used for clarity) --Look at the first line of tweet.rb (tweet model). Did you understand the class name? ――In other words, "self.search (search)" is ** "" Tweet.search (search) "**. (Like I saw it somewhere)
Did you understand somehow? ??
--The "Tweet.search (params [: keyword])" used in the controller is the same as the ** self.search (search) "** method you created in the model.
In fact, various methods such as "find method" and "include method" that we often use Just like I made my own "search method" this time, ** Rails' ActiveRecord made it **! !!
** Each model inherits ActiveRecord **, so you can use methods in your controller! (Strictly speaking, class Tweet <ApplicationRecord <ActiveRecord :: Base) If you look at the first line of tweet.rb (tweet model), you can see it.
Well, it's getting longer, but there is one who hasn't solved it yet. Yes, what was "self = class method" after all?
Class methods are literally methods that can be used for "classes". Can you remember what a "class" was? ?? If you don't know, take a look at the first line of tweet.rb (tweet model).
** I still don't understand any more! !! Lol**
It may have been a bit confusing, but please forgive me because I have been programming for 2 months. (I was able to organize my head relatively.) I've written this for a long time, but thank you for reading to the end.
If the interpretation is wrong, I would be very grateful if you could let me know.
More and more.
Recommended Posts