【发布时间】:2017-11-25 18:02:49
【问题描述】:
您认为检索 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 实例上的方法来检索所有关联的属性:
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 => { ... }, ....
}
目前我通过迭代每个关联,然后对关联的每个模型进行迭代来完成这项工作,但这有点贵,你认为我可以如何优化这个?
请注意:我意识到你不能在 has_many 与 nested_attributes 的关联上调用 target.countries_attributes,one_to_one 关联允许调用 target.country_attributes
【问题讨论】:
标签: ruby-on-rails activerecord