我对如何从 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 类的方法中使用发送来在内部设置这些属性,如下所示:
def instance_method(prop)
self.send("#{prop}=".to_sym, value_node.text)
end
我的问题是如何在 ActiveRecord 实例本身内访问这些 :phone_1、:phone_2 属性而不必使用发送,这是我能想到的唯一方法。我认为当从公共(public)接口(interface)访问这些属性时,可以通过 method_missing 访问这些属性:
puts lead.phone_1
但除了通过发送之外,我不知道如何从 ActiveRecord 实例中访问它们。
这可能吗?
最佳答案
您可以直接从任何 AR 实例中引用 AR 属性。不需要任何“发送”魔法:
def some_method
self.some_attribute='value' # with or without self
x = some_attribute
end
是什么让您不这么认为?
如果您需要绕过 AR 的内置访问器,您可以使用 read_attribute 和 write_attribute。
关于ruby-on-rails - 从 ActiveRecord 实例中访问 RoR ActiveRecord 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3946329/