0

如何获取所有一种类型的列表?
例如,所有字符串属性的列表?有没有简单的 Virtus 解决方案,还是我必须自己动手?

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]

或者有没有其他方法可以获取列表形式的所有字符串属性?

我的最终目标是能够根据类型将属性分解为各种验证。

4

1 回答 1

0

您可以使用该attribute_set方法以及primitive获取属性 Class ,然后您需要编写自己的方法:

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̶r̶̶y̶o̶u̶̶c̶a̶n̶̶g̶o̶̶a̶̶s̶t̶e̶p̶̶f̶u̶r̶t̶h̶e̶r̶̶a̶n̶d̶̶u̶s̶e̶̶d̶e̶f̶i̶n̶e̶m̶e̶t̶h̶o̶d̶_̶m̶i̶s̶s̶i̶n̶g̶̶l̶i̶s̶t̶n̶g̶̶l̶i̶s̶k̶t̶h̶

我希望这就是你要找的。

于 2016-03-18T20:51:06.300 回答