【问题标题】:Accessing a RoR ActiveRecord's attributes from within the ActiveRecord instance从 ActiveRecord 实例中访问 RoR ActiveRecord 的属性
【发布时间】: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


    【解决方案1】:

    您可以直接从任何 AR 实例中引用 AR 属性。不需要任何“发送”魔法:

    def some_method
     self.some_attribute='value' # with or without self
     x = some_attribute
    end
    

    是什么让你不相信?

    如果您需要绕过 AR 的内置访问器,您可以使用 read_attribute 和 write_attribute。

    【讨论】:

    • 这是漫长的一天。我想我需要把笔记本电脑收起来:-)
    【解决方案2】:

    您可以只使用self.phone1self.phone2/ 例如:

    class Lead < ActiveRecord::Base
    
      def some_instance_method
        self.phone1 = '1234567'
        self.phone2 = self.phone1
      end
    
    end
    

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多