What do you think is the best way to get all the attributes for all the associations that the AR model has?
ie: let's say we have a Target model.
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
I would like to get all the association attributes by calling the method on the Target instance:
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 => { ... }, .... }
I am currently doing this work, iterating through each association, and then through each association model, but it is somehow expensive. Do you think I can optimize this?
Just a note: I realized that you cannot name target.countries_attributes in has_many associations with associations nested_attributes , one_to_one to call target.country_attributes
ruby-on-rails activerecord
jpemberthy
source share