modelã¯ã©ã¹ã®ä¸ã§ã®selfã®ä½¿ãæ¹
modelã¯ã©ã¹ã®ä¸ã§ã®selfã®ä½¿ãæ¹ã§ããrailsã®ã«ã¼ã«ã¨ããããã¯rubyã®ã«ã¼ã«ã§ãããmodelã®ä¸ã§selfã使ãã¨ãã«æã
ä¸å®ã«ãªãã®ã§ã¡ã¢ã£ã¦ããã¾ãã
ã¯ã©ã¹ã¡ã½ããã¨ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã
modelã¯ã©ã¹ã®ä¸ã§ã¡ã½ãããå®ç¾©ããéã«ãã¡ã½ããåã®é ã«self.ãã¤ããã¨ã¯ã©ã¹ã¡ã½ãããã¤ããªãã¨ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã«ãªãã¾ãã
class User < ActiveRecord::Base def hoge #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã end def self.hoge #ã¯ã©ã¹ã¡ã½ãã (def User.hoge ã¨ãã£ã¦ãåãæå³) end end
ã¡ãªã¿ã«ä½¿ãåãã§ãããã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã¯ããããã®ã¤ã³ã¹ã¿ã³ã¹ã«å¯¾ãã¦åç
§ã»æ´æ°ãããããªã¡ã½ããã¨ãã¦ä½¿ãã¾ããä¸æ¹ã¯ã©ã¹ã¡ã½ããã¯ãmodelã¯ã©ã¹ã®ã¬ã³ã¼ããæ¤ç´¢ããã¨ããä½æãããã¤ã³ã¹ã¿ã³ã¹ã®æ°ãã«ã¦ã³ãããã¨ããã¯ã©ã¹ã®æ°ããã¤ã³ã¹ã¿ã³ã¹ãä½ãçãåã
ã®ã¤ã³ã¹ã¿ã³ã¹ã«ã¯ç´ã¥ããã¯ã©ã¹ã«å¯¾ãã¦åããããã¡ã½ããã«ãªãã¾ãã
ã¡ã½ããå ã§selfã使ãå ´å
ã¯ã©ã¹ã¡ã½ããå ã§selfã使ãã¨ã¯ã©ã¹ãæããã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããå ã§selfã¯ãã®ã¤ã³ã¹ã¿ã³ã¹ã«ãªãã¾ãããªã¼ãºããã«ã§ããã
class User < ActiveRecord::Base def hoge #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã end def self.hoge #ã¯ã©ã¹ã¡ã½ãã end def page #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã self.hoge #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã®hogeãå¼ã°ãã hoge #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã®hogeãå¼ã°ãã self.class.hoge #ããããã¨ã¯ã©ã¹ã¡ã½ããã®hogeãå¼ã¹ã end def self.page #ã¯ã©ã¹ã¡ã½ãã self.hoge #ã¯ã©ã¹ã¡ã½ããã®hogeãå¼ã°ãã hoge #ã¯ã©ã¹ã¡ã½ããã®hogeãå¼ã°ãã end end
ã¡ãªã¿ã«ã¯ã©ã¹ã¡ã½ããã class << self ã®ä¸ã§å®ç¾©ãããã¨ãã§ããã®ã§ãã¯ã©ã¹ã¡ã½ããã¨ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãããããã¤ãå
¥ãä¹±ããã¨ãã¯ãä¸ã®ããã«æ¸ãæ¹ãè¦éããããããããã¾ããã
class User < ActiveRecord::Base def hoge #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã end def page #ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ãã end class << self def page #ã¯ã©ã¹ã¡ã½ãã end def hoge #ã¯ã©ã¹ã¡ã½ãã end end end