LoginSignup
11

More than 5 years have passed since last update.

ActiveRecordのattributeとalias_method_chain

Last updated at Posted at 2013-04-25

dbでは文字列型のカラムをsymbolとして引きたくて、alias_method_chainを使ってgetterでラップしたらいいのでは?と思ったら軽くつまづいたのでメモ。意外と日本語情報なかった。

テーブル hoges には `fuga` text が定義されているとする。

class Hoge < ActiveRecord::Base 
  attr_accessible :fuga
end

def fuga_with_to_sym
  fuga_without_to_sym.to_sym
end

alias_method_chain :fuga, :to_sym

怒られた。

NameError (undefined method `fuga' for class `Hoge'):

解決法はここにあった。

class Hoge < ActiveRecord::Base 
  attr_accessible :fuga
end

def fuga
  super
end

def fuga_with_to_sym
  fuga_without_to_sym.to_sym
end

alias_method_chain :fuga, :to_sym

これで Hoge#fuga はsymbolを返してくれる。nilが入らないよう注意しよう。

ちなみに解決法についてるリプライ「attr_accessor使えばいいんじゃね?」って言ってる。確かにNameErrorは出なくなるけど、それは@fugaへのアクセサなので意味がないのでした。

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
11