2012-11-05 40 views
0

我有一個基本上有一堆布爾列的amenities模型。在導軌模型中過濾錯誤的列

我想在視圖中顯示真正的列,所以我想在模型級別過濾出錯誤的列。

我的初步想法:

# 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列。

我覺得必須有更好的方法來實現這一點。

回答

0

使用@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 
1

我認爲迭代self.attributes是一個好主意。您可以更嚴格地測試value以過濾掉非布爾列。

a[key] = value if [TrueClass, FalseClass].include? value.class