2012-01-11 47 views
0

Rails 3.0.3應用程序。 。 。Rails:在驗證期間導致錯誤的虛擬屬性讀取器

我在模型中使用虛擬屬性來根據用戶的偏好(美國或公制單位)轉換存儲在數據庫中的值以供顯示。我在閱讀器方法中進行轉換,但是當我測試我的存在驗證時,我得到一個NoMethodError,因爲真實屬性爲零。下面的代碼:

class Weight < ActiveRecord::Base 
    belongs_to :user 

    validates :converted_weight, :numericality => {:greater_than_or_equal_to => 0.1} 

    before_save :convert_weight 

    attr_accessor :converted_weight 

    def converted_weight(attr) 
    self.weight_entry = attr 
    end 

    def converted_weight 
    unless self.user.nil? 
     if self.user.miles? 
     return (self.weight_entry * 2.2).round(1) 
    else 
     return self.weight_entry 
    end 
    else 
    return nil 
    end 
end 
... 

這是造成問題的行:

return (self.weight_entry * 2.2).round(1) 

我明白爲什麼self.weight_entry是零,但什麼是處理這個最好的方法是什麼?我應該拋出一個除非self.weight_entry.nil嗎?檢查讀者?或者我應該在其他地方執行此轉換? (如果是的話,在哪裏?)

謝謝!

+0

想要使用兩個名稱相同(converted_weight)但輸入參數不同(「方法重載」)的方法是否正確? – 2012-01-11 16:12:17

+0

我的理解是一個是吸氣劑,另一個是固定劑方法。從我對Rails有限的理解來看,我的setter可能不是必需的(Rails通過attr_accessor helper處理)。我需要做的是將其值從公制數值(公斤)轉換爲美國單位(磅)。我最初的猜測是在虛擬屬性的getter方法中這樣做,但是當我測試虛擬屬性的存在時,它在驗證過程中爆炸了,因爲還沒有weight_entry值。至少這是我認爲正在發生的事情。 – jacoulter 2012-01-12 13:48:10

+0

我想我對'converted_weight'的命名感到困惑。你能顯示你的表單代碼嗎? 'weight_entry'是否被表單傳遞,並且它是否應該存儲在數據庫中? – 2012-01-12 14:55:56

回答

0

這裏是我做了什麼:

型號

validates :weight_entry, :numericality => {:greater_than_or_equal_to => 0.1} 

before_save :convert_weight 

attr_reader :converted_weight 

def converted_weight 
    unless self.user.nil? 
    unless self.weight_entry.nil? 
     if self.user.miles? 
     return (self.weight_entry * 2.2).round(1) 
     else 
     return self.weight_entry 
     end 
    end 
    else 
    return nil 
    end 
end 

形式

<%= f.label :weight_entry, 'Weight' %><br /> 
<%= f.text_field :weight_entry, :size => 8, :value => @weight.converted_weight %> <strong><%= weight_units %></strong> (<em>Is this not right? Go to your <%= link_to 'profile', edit_user_registration_path %> to change it</em>) 

unless.self.weight_entry.nil?檢查允許驗證,做的工作。如果有人知道更好的方法來做到這一點,我願意提供建議。

謝謝!

P.S. before_save convert_weight方法將美國單位轉換爲度量標準。我想一直以相同的單位存儲值,所以如果用戶以後更改了她的偏好,以前存儲的值不會失效。