【问题标题】:how to delay the creation of the association until the subclass is created in active record?如何延迟关联的创建,直到在活动记录中创建子类?
【发布时间】:2009-08-09 14:14:11
【问题描述】:

我有四个表:jp_properties、cn_properties、jp_dictionaries 和 cn_dictioanries。

每个 jp_property 都属于一个 jp_dictionary,表中有外键“dictionary_id”。

同样,每个cn_property都属于一个cn_dictionary,表中的外键为“dictionary_id”。

由于属性模型和字典模型中都有很多相同的函数,我想将所有这些函数分组到 abstract_class 中。

模型是这样的:

class Property < AR::Base
  self.abstract_class = true
  belongs_to :dictionry,
             :foreign_key=>'dictionary_id',
             :class=> ---ModelDomainName--- + "Dictionary"

  ### functions shared by JpProperty and CnProperty
end

class Dictionary < AR::Base
  self.abstract_class = true
  has_many :properties,
           :foreign_key=>'dictionary_id',
           :class=> ---ModelDomainName--- + "Dictionary"

  ### functions shared by JpDictionary and CnDictionary
end

class JpProperty < Property
  :set_table_name :jp_properties
end

class CnProperty < Property
  :set_table_name :cn_properties
end

class JpDictionary < Dictionary
  :set_table_name :jp_dictionaries
end

class CnDictionary < Dictionary
  :set_table_name :cn_dictionaries
end

从上面的代码可以看出,---ModelDomainName--- 部分要么是'Jp',要么是'Cn'。 我想从 JpProperty、JpDictionary、CnProperty 或 CnDictionary 的实例中动态获取这些字符串。

例如:

tempJpProperty = JpProperty.first
tempJpProperty.dictionary #=> will get 'Jp' from tempJpProperty's class name and then apply it to the "belongs_to" declaration.

所以问题是我不知道如何指定 ---ModelDomainName--- 部分。

更具体地说,我不知道如何在父类的主体中获取子类的实例对象的类名。

你能帮我解决这个问题吗?

编辑:

有人有什么想法吗?

基本上,我想问的是如何'将关联的创建延迟到 子类已创建。'?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    你应该可以做这样的事情:

    class Property < AR::Base
      self.abstract_class = true
      belongs_to :dictionry,
                 :foreign_key=>'dictionary_id',
                 :class=> #{singlenton_class} + "Dictionary" 
    
      def singlenton_class
         class << self; self; end 
      end  
    end
    

    【讨论】:

    • 感谢您的回复。我试过你的建议。但我没有运气。
    猜你喜欢
    • 1970-01-01
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多