3
設定テーブル内のクラスメソッドを定義します。はスキーマからのActive Recordクラス
create_table "settings", :force => true do |t|
t.string "name"
t.string "value"
t.datetime "created_at"
t.datetime "updated_at"
end
設定テーブルには、これらのレコードを持っている:
{name: "notification_email", value: "[email protected]"}
{name: "support_phone", value: "1234567"}
私は "ハローを返すためにSetting.notification_email機能をしたいです@ monkey.com "、それぞれSetting.support_phoneは" "。
class Setting < ActiveRecord::Base
class << self
all.each do |setting|
define_method "#{setting.name}".to_sym do
setting.value.to_s
end
end
end
end
しかし、私は、コンソールでSetting.notification_emailを入力するときに、それは私にエラー与える::
NameError: undefined local variable or method `all' for #<Class:0x000000053b3df0>
from /home/adam/Volumes/derby/app/models/setting.rb:7:in `singletonclass'
from /home/adam/Volumes/derby/app/models/setting.rb:2:in `<class:Setting>'
from /home/adam/Volumes/derby/app/models/setting.rb:1:in `<top (required)>'
...
'define_singleton_method'は1.9です。 1.8と同等のものは 'self.class.instance_eval'と' define_method'を組み合わせたものです。これはきれいにされているニース。 – tadman