Ruby on rails 如何获取保存在实例变量中的模型属性

Ruby on rails 如何获取保存在实例变量中的模型属性,ruby-on-rails,activerecord,ruby-on-rails-3,Ruby On Rails,Activerecord,Ruby On Rails 3,我正在写一个插件,在插件中我动态地定义了一个新的关系。下面给出了示例代码 module AttachDocumentsAs @as = nil def attach_documents_as(*attachment_as) attachment_as = attachment_as.to_a.flatten.compact.map(&:to_sym) @as = attachment_as.first class_inh

我正在写一个插件,在插件中我动态地定义了一个新的关系。下面给出了示例代码

module AttachDocumentsAs
   @as = nil
   def attach_documents_as(*attachment_as)
      attachment_as = attachment_as.to_a.flatten.compact.map(&:to_sym)
      @as           = attachment_as.first
      class_inheritable_reader(@as)

      class_eval do
          has_many @as, :as => :attachable, :class_name=>"AttachDocuments::Models::AttachedDocument"
          accepts_nested_attributes_for @as
      end 
   end
end
现在在任何模型中,我都使用它作为

class Person < AtiveRecord::Base
    attach_documents_as :financial_documents
end
但是它没有得到必需的属性,有人能帮我吗。我想建立这个关系并设置一些初始值


等待大家的指导。

您可能混淆了
@as
类实例变量(仅对Person类方法可用)和
@as
实例变量(仅对此类实例可用)。我知道,即使这样的解释听起来也有点复杂

每个对象都有实例变量,类只是对象的一种类型。此类的实例也是对象,它们有自己的独立实例变量。要从类的实例中获取类实例变量,您需要一个reader方法,就像您定义的那样。也许你的意思是:

def initialize(*args)
  super(*args)

  # self.class.as returns something like :financial_documents, so use this method
  # to return a scope to build in.
  send(self.class.as).build
end
您使用
@as
的方式表明您已经习惯了PHP或Perl之类的东西,您可以像使用
${$as}
一样取消引用它。在Ruby中,您通常将字符串或符号反引用到类或方法中

看起来您正在尝试将符号转换为方法调用,这是通过
send
完成的


如果您试图将字符串转换为类,您可以对字符串使用
constantize
方法,这是Rails环境的一项功能。

我使用class_可继承_读取器(@as)class_可继承_读取器(:atd_as)write_可继承_属性(:atd_as,@as),现在在初始化中,我可以将其作为self.send(self.send(:atd_as))获取但是现在的问题是调用它的构建self.send(self.send(:atd_as))。构建不起作用。
def initialize(*args)
  super(*args)

  # self.class.as returns something like :financial_documents, so use this method
  # to return a scope to build in.
  send(self.class.as).build
end