【发布时间】:2012-05-22 22:42:51
【问题描述】:
我对如何从 ActiveRecord 实例中的方法访问 ActiveRecord 实例的属性感到困惑。
例如,我有一个从 ActiveRecord 继承的 Lead 类:
class Lead < ActiveRecord::Base
end
我有以下按比例缩小的迁移文件,其中显示了 ActiveRecord 表的列:
class CreateLeads < ActiveRecord::Migration
def self.up
create_table :leads do |t|
t.string :phone_1
t.string :phone_2
t.string :web
t.string :fax
t.timestamps
end
end
def self.down
drop_table :leads
end
end
我在 Lead 类的方法中使用 send 在内部设置这些属性,如下所示:
def instance_method(prop)
self.send("#{prop}=".to_sym, value_node.text)
end
我的问题是如何在 ActiveRecord 实例本身中访问这些 :phone_1, :phone_2 属性,而不必使用 send 这是我能想到的唯一方法。我认为这些属性是通过 method_missing 从公共接口访问它们时访问的,如下所示:
puts lead.phone_1
但我不知道如何从 ActiveRecord 实例中访问它们,除了通过发送。
有可能吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3