Reputation: 481
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
Upvotes: 0
Views: 56
Reputation: 4920
Try this:
associations.each do |key, value|
...
if value.macro == :belongs_to # OR you can do `value.relation == Mongoid::Relations::Referenced::In`
selected_associations.push(key) # OR `value`, you need to decide what you need here
end
end
key
is the name of association here e.g. "user".
value
looks something like this:
#<Mongoid::Relations::Metadata
autobuild: false
class_name: User
cyclic: nil
counter_cache:false
dependent: nil
inverse_of: nil
key: user_id
macro: belongs_to
name: user
order: nil
polymorphic: false
relation: Mongoid::Relations::Referenced::In
setter: user=
versioned: false>
Upvotes: 1