如何获得所有一种类型的列表?
例如,所有字符串属性的列表?有一个简单的解决方案,还是我必须自己滚动?
def my_model
include Virtus.model
attribute :a, Integer
attribute :b, Integer
attribute :c, String
attribute :d, String
attribute :w, Float
attribute :j, Float
end我想从本质上讲做my_model.something = [:c, :d]
或者是否有其他方法以列表形式获取所有字符串属性?
我的最终目标是能够将属性分割成基于类型的各种验证。
发布于 2016-03-18 20:51:06
您可以使用attribute_set方法和primitive获得属性类,然后需要编写自己的方法:
def self.get_string_attributes
attributes = []
self.attribute_set.each do |attribute|
attributes << attribute.name if attribute.primitive == String
end
attributes
end我从你的MyModel上得到了这个结果
MyModel.get_string_attributes
=> [:c, :d]O̶m̶e̶t̶h̶o̶d̶_̶m̶i̶s̶s̶i̶n̶g̶r̶r̶̶y̶o̶u̶̶c̶a̶n̶̶g̶o̶̶a̶̶s̶t̶e̶p̶̶f̶u̶r̶e̶a n d̶̶u,e_e_d_d_i_(E),e_d_d_e_e_f_(F),e_b,b,e,b,e,b,b,e,b,t,b,t,t,b,t,b,t,t,
我希望这就是你要找的。
https://stackoverflow.com/questions/36091525
复制相似问题