I create dynamic classes for my models using rails/mongoid. I want to automatically include certain associated records (belongs_to, has_one) whenever I access a record. Therefore I need to include all these association in my as_json function.
The method 'associations' gives me all associated models - but I need to filter only the type of associations I want to include (if I include the has_many association I will get a huge time consuming database request and I dont need these data). How can I filter the output of the the association method to get only the required associations?
I tried to loop through all associations:
def as_json(options={})
selected_associations=[]
associations.each do |ass|
puts "Association:: ", ass, ass=>relation
if association=='Belongs_To' # Need the right instruction here
selected_associations.push(ass)
end
end
attrs = super(:include => selected_associations)
end
Puts delivers me for each association following output on the console (entity is one model):
Association: entities {:relation=>Mongoid::Relations::Referenced::Many, :extend=>nil, :inverse_class_name=>"WSAEntity", :name=>"entities", :class_name=>"WSAEntity", :validate=>true}
How can I assess the ':relation=>...' attribute so I can use this to select the types of associations I need and correct my code above? Or there is an even better way to get an array with all my filtered associations?
Thanks, Michael