class Category
has_many :posts
has_many :images
end
是否可以在不明确写出相关模型的复数形式的情况下链接下面的关系?如果可能的话,论证应该是什么类型的?
def get_all(children_of_certain_model)
self.children_of_certain_model.size
end
# one_category.get_all(:posts)
我知道对于上面这种情况,我可以直接简单地调用one_category.posts
,但我一般都很好奇,如果它可以抽象出链式关系。
答案 0 :(得分:1)
正如@Sergio Tulentsev建议的那样,您可以使用public_send
仅使用符号语法调用公共方法。您也可以只使用send
,但也可以设置允许输出关联的列表(当然,行为不等同于):
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