While learning Ruby, I saw a lot of code with patterns of ○○. △△ (example: User.new). I wondered if they were used differently, and found three patterns of usage. So, this time I have summarized the patterns of ○○. △△.
A fledgling engineer learning Ruby
Ruby 2.6.5 Rails 6.0.3.3
Used for table operations on models. In the example below, it is the part of "Tweet.all", "Tweet.new", "Tweet.find (params [: id])".
class TweetsController < ApplicationController
def index
Get all data of #Tweet model (Tweets table)
@tweet = Tweet.all
end
def new
Instantiation of #Tweet model
@tweet = Tweet.new
end
def edit
Get one data (1 record) with #Tweet model (Tweets table)
@tweet = Tweet.find(params[:id])
end
end
See this article for the ActiveRecord method. It was really easy to understand. https://qiita.com/ryokky59/items/a1d0b4e86bacbd7ef6e8
Use the method by attaching it to the instance. Instance methods cannot be used without creating an instance. In the example below, it is the "number.calc (1,2)" part.
class Number
def calc(a, b)
puts a + b
end
end
number = Number.new()
number.calc(1,2)
It is used to get the attribute value stored in the variable. In the example below, it is the "user.nickname" part. Gets the data in the nickname column of the User table.
class UsersController < ApplicationController
def show
Get one data (1 record) with #User model (Users table) and assign it to variable user
user = User.find(params[:id])
Get the information (attribute value) of the nickname column of the #variable user and assign it to the instance variable @nickname.
@nickname = user.nickname
end
end
That's it. I'm glad if you can use it as a reference.
Recommended Posts