true do |t| t.string "name" t.string "value" t-6ren">
gpt4 book ai didi

ruby-on-rails - 在 Active Record 类中定义类方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:15 25 4
gpt4 key购买 nike

模式中的设置表:

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: "hello@monkey.com"}
{name: "support_phone", value: "1234567"}

我希望 Setting.notification_email 函数返回“hello@monkey.com”,Setting.support_phone 函数返回“1234566”。

这是我的 setting.rb 中的内容:

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 - 即

class Setting < ActiveRecord::Base

self.all.each do |instance|
define_singleton_method(instance.name) do
instance.value.to_s
end
end
end

关于ruby-on-rails - 在 Active Record 类中定义类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10082237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com