Ruby on rails rails模型中的假列过滤
我有一个便利设施模型,基本上有一堆布尔列Ruby on rails rails模型中的假列过滤,ruby-on-rails,Ruby On Rails,我有一个便利设施模型,基本上有一堆布尔列 a[key] = value if [TrueClass, FalseClass].include? value.class 我希望在视图中显示真实列,因此我希望在模型级别过滤掉虚假列 我最初的想法是: # in model file def available a = {} self.attributes.each do |key, value| if value a[key] = value
a[key] = value if [TrueClass, FalseClass].include? value.class
我希望在视图中显示真实列,因此我希望在模型级别过滤掉虚假列
我最初的想法是:
# in model file
def available
a = {}
self.attributes.each do |key, value|
if value
a[key] = value
end
end
a
end
这并不完美,因为它为我提供了id、created_at和modified_at列
我觉得一定有更好的方法来实现这一点。我认为迭代
self.attributes
是个好主意。您可以更严格地测试value
以过滤掉非布尔列
a[key] = value if [TrueClass, FalseClass].include? value.class
使用@Deefour建议,我得出以下结论:
def available
a = {}
hidden = ["id","created_at","updated_id","business_id"]
self.attributes.each do |key, value|
a[key] = value if value.class == TrueClass
a[key] = value if [String].include? value.class and not value.empty?
a[key] = value if not hidden.include? key and value.class == Fixnum
end
a
end