1
0

More than 3 years have passed since last update.

クラス内における同一クラスに対するクラスメソッドのクラス省略について(備忘録)

Last updated at Posted at 2021-02-17

概要

初学者のただの備忘録です。

環境

  • Ruby: 2.6.6
  • Rails: 6.0.3.5

実装

例えば下記のようなCategoryクラスでhogehogeというクラスメソッドを定義する。

app/models/category.rb
class Category < ApplicationRecord

  def self.hogehoge
    category = Category.find_by(name: category_name)
    return category.ideas if category.present?
    []
  end

end

hogehogeメソッドの1行目Category.find_by(name: category_name)は
Categoryというクラス(class Category < ApplicationRecord)で
hogehogeメソッドの中で
Categoryクラスに対してfind_by(name: category_name)している。
だからクラスを省略できる。

category = Category.find_by(name: category_name)
category = find_by(name: category_name)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0