2012-10-23 45 views
1

任何想法如何才能使其發揮作用?我不能爲我的生活弄清楚。Rails:訪問使用column_names選擇的列的值

def get_prices(c) 
    @print_prices = {} 
    Billing.where(:name => c).column_names.each do |d| 
    if d.match(/^print_/) 
     @print_prices[d] = d.value 
    end 
    end 
    return @print_prices 
end 

我不知道用什麼來代替d.value

乾杯任何幫助。

+0

究竟是什麼你想在這裏做什麼? –

+0

我正在嘗試構建值的散列,即'{「print_100」=>「30」,「print_200」=>「60」,「print_500」=>「90」}'。關鍵是列名,值是列的值。 –

+0

你期望'Billing.where(:name => c)'只返回關係中的一條記錄嗎? –

回答

1

以下代碼將執行以關係形式返回的查詢,並拒絕屬性鍵值散列中與給定正則表達式不匹配的所有項目,在本例中爲/^print_/

def get_prices(c) 
    Billing.where(:name => c).first.attributes.reject{ |i| !i.match(/^print_/) } 
end 

或者,也可以寫爲:

def get_prices(c) 
    Billing.where(:name => c).first.attributes.select{ |i| i.match(/^print_/) } 
end 
+0

乾杯!很棒。是的,雙重否定總是令人困惑。哈。 –