Help us understand the problem. What is going on with this article?

ApplicationRecordで定義した関数を呼ぼうとしたらハマった

ApplicationRecordで定義した関数をControllerで呼ぼうとしたらハマったので、メモ
(プロジェクトはAPIモード)

呼び出し元(例)

login_controller.rb
class LoginsController < ApplicationController
    def login
        user = User.find_user(params[:login_id], params[:password])

        render json: user
    end
end

呼べなかったやつ(例)

定義されてないよって怒られた。

User.rb
class User < ApplicationRecord
    def find_user(login_id, password)
        return self.find_by(login_id: login_id, password: password)
    end
end

呼べたやつ(例)

関数名にself.をつけたら呼べた。

User.rb
class User < ApplicationRecord
    def self.find_user(login_id, password)
        return self.find_by(login_id: login_id, password: password)
    end
end

終わり

クラスメソッドとインスタンスメソッドっていうのがあるらしく、
今回の呼び出し方では、クラスメソッドとして定義しないといけないらしい。

self.をつけない場合は、下記のようにnewして、

login_controller.rb
class LoginsController < ApplicationController
    def login
        user_instance = User.new()
        user = user_instance.find_user(params[:login_id], params[:password])

        render json: user
    end
end

ApplicationRecordではUser.find_byで呼ばないといけないみたい。

User.rb
class User < ApplicationRecord
    def find_user(login_id, password)
        return User.find_by(login_id: login_id, password: password)
    end
end

個人的には呼び出し方としては、クラスメソッドが好きかな

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away