Reputation: 34073
class Category
has_many :posts
has_many :images
end
Is it possible to chain a relation like below without explicitly write the plural form of the associated model? And if possible, of what type should the argument be?
def get_all(children_of_certain_model)
self.children_of_certain_model.size
end
# one_category.get_all(:posts)
I know that for the case above I could simple call one_category.posts
directly, but I'm just curious in general if it at all is possible to abstract the chained relation.
Upvotes: 1
Views: 62
Reputation: 44601
As @Sergio Tulentsev suggested, you can use public_send
to call only public methods with symbol syntax. You can also use just send
, but also set a list of permitted for output associations (the behaviour is not equivalent, of course):
class Category
has_many :posts
has_many :images
has_many :emails
end
def get_all(association)
self.send(association).size if association.in?([:posts, :images])
end
one_category.get_all(:emails) #=> nil
Upvotes: 1