你認爲什麼是檢索AR模型所有關聯的所有屬性的最佳方法?檢索AR模型的所有關聯屬性?
即:假設我們有型號Target
。
class Target < ActiveRecord::Base
has_many :countries
has_many :cities
has_many :towns
has_many :colleges
has_many :tags
accepts_nested_attributes_for :countries, :cities, ...
end
我想通過調用一個方法上的目標實例,以檢索該協會的所有屬性:
target.associations_attributes
>> { :countries => { "1" => { :name => "United States", :code => "US", :id => 1 },
"2" => { :name => "Canada", :code => "CA", :id => 2 } },
:cities => { "1" => { :name => "New York", :region_id => 1, :id => 1 } },
:regions => { ... },
:colleges => { ... }, ....
}
目前我做這項工作是通過遍歷每個關聯,然後對每個模型該協會,但它是昂貴的,你認爲我可以優化這個?
剛一說明:我意識到,你不能叫target.countries_attributes
上has_many
協會與nested_attributes
,one_to_one
關聯允許調用target.country_attributes
是的,我使用的是反射,但是這種方法更加優化,只有一件事,我從'object_or_array = me.send(association_name).all'中刪除了'all'這並不是真的必要,如果有' one_to_one'關係。謝謝! – jpemberthy 2010-02-19 20:43:27
好,我編輯了這個例子。並沒有問題。 :) – 2010-02-19 20:45:13