Ruby on rails 从ruby中的类名列表中按属性提取对象

Ruby on rails 从ruby中的类名列表中按属性提取对象,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有一个类名列表:obj_list=[水果,蔬菜] 我需要迭代它们,找到所有颜色属性设置为红色的对象,假设水果和蔬菜都有这个属性 这将设置@fruits和匹配颜色的水果对象列表:“red”,并设置@vegets和匹配颜色的蔬菜对象列表:“red” 希望这有帮助您也可以这样做: obj_list = ["Fruit", "Vegetable"] obj_list.each_with_object(Array.new){ |object, array| array.push(object.cons

我有一个类名列表:obj_list=[水果,蔬菜] 我需要迭代它们,找到所有颜色属性设置为红色的对象,假设水果和蔬菜都有这个属性

这将设置@fruits和匹配颜色的水果对象列表:“red”,并设置@vegets和匹配颜色的蔬菜对象列表:“red”


希望这有帮助

您也可以这样做:

obj_list = ["Fruit", "Vegetable"]

obj_list.each_with_object(Array.new){ |object, array| array.push(object.constantize.send(:where, {color: 'red'})) }

它将是活动记录关系的数组,包含水果和蔬菜。

发布您到目前为止所做的事情。每个{c|Kernel.get|constc.wherecolor=red}它是const|u get,您是否为类定义了where方法?另外,颜色属性是类属性还是对象属性?水果和蔬菜Rails模型吗?每个带有\u objectArray.new和push的\u只是映射。
obj_list = ["Fruit", "Vegetable"]

obj_list.each_with_object(Array.new){ |object, array| array.push(object.constantize.send(:where, {color: 'red'})) }