1
我有以下幾點:在哪裏把我的紅寶石課堂類「元生成器」?
class ThirdParty < ActiveRecord::Base
# Dynamically adds accessors of the requested kind.
def self.has_many_children_of_kind (kinds=[])
puts 'In generator method'
kinds.each { |k|
n = k.to_s
self.class_eval %{
has_many :#{n}_as_owner, {
:foreign_key => :owner_id,
:class_name => 'ThirdPartiesLink',
:conditions => #{ k!=:third_parties ? "{ :kind => '"+n.singularize+"' }" : 'nil' }
}
has_many :#{n}, {
:through => :#{n}_as_owner,
:source => :owned
}
}
}
end
# Make dynamic associations of given kinds.
has_many_children_of_kind [ :third_parties, :customers, :suppliers, :contacts ]
end
class ThirdPartiesLink < ActiveRecord::Base
belongs_to :owner, :foreign_key => :owner_id, :class_name => 'ThirdParty'
belongs_to :owned, :foreign_key => :owned_id, :class_name => 'ThirdParty'
# This model has a column named 'kind' for storing the link kind.
end
一切工作完全按照我的期望。 線:
has_many_children_of_kind [ :third_parties, :customers, :suppliers, :contacts ]
生成:
has_many :third_parties_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => nil }
has_many :third_parties, { :through => :third_parties_as_owner, :source => :owned }
has_many :customers_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => { :kind => 'customer' } }
has_many :customers, { :through => :customers_as_owner, :source => :owned }
has_many :suppliers_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => { :kind => 'supplier' } }
has_many :suppliers, { :through => :suppliers_as_owner, :source => :owned }
has_many :contacts_as_owner, { :foreign_key => :owner_id, :class_name => 'ThirdPartiesLink', :conditions => { :kind => 'contact' } }
has_many :contacts, { :through => :contacts_as_owner, :source => :owned }
然而,每次我刷新,其中第三方對象使用的,「線發生器方法」在控制檯被outputed的頁面。
我已經試過幾件事情: puting的has_many_children_of_kind在我的應用程序的初始化,而不是把它在第三方類的(我真的不喜歡的是,它更多的是測試比什麼都重要的)。在這種情況下,頁面的第一個顯示器在服務器重新啓動後工作,但如果我刷新頁面,在ThirdParty實例上調用時未找到生成的方法...
什麼是確保ThirdParty類在服務器啓動時一次全部使用訪問器寫入?
謝謝你的時間! Pierre。
編輯:發電機方法塊也可以是這樣的:
kinds.each { |k|
n = k.to_s
has_many("#{n}_as_owner".to_sym, {
:foreign_key => :owner_id,
:class_name => 'ThirdPartiesLink',
:conditions => (k!=:third_parties ? { :kind => n.singularize } : nil)
}
)
has_many(n.to_sym, {
:through => "#{n}_as_owner".to_sym,
:source => :owned
}
)
}
什麼是最好的?評估還是最新?我會說最新的,因爲沒有涉及解析器/評估,所以它可能會更快一點,對吧?
嘗試在development.rb中設置config.cache_classes = true。很可能你只是看到每個請求上重新加載類。 – mnelson 2011-03-22 04:24:01
這是一個實際的工作解決方案!非常感謝,我不知道這種緩存機制。 – Doodloo 2011-03-23 02:44:18