Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Rails modelでselfの使い方

More than 1 year has passed since last update.

modelでいつselfを付けるべきかがふんわりするので、まとめました。

簡単に言うとクラスメソッドとして使いたい場合はselfを付ける、インスタンスメソッドとして使いたい場合はselfを付けない

class Sample < ApplicationRecord
  #Sample.class_methodでこのメソッドを呼ぶ
  def self.class_method
    "class_method"
  end

  #sample = Sample.new
  #sample.instance_methodの形でメソッドを呼ぶ
  def instance_method
    "instance_method"
  end
end
pakushiken
東京で働いている中国人エンジニア
Why not register and get more from Qiita?
  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