2009-12-24 66 views
0

我在活動記錄文件中有以下代碼。ActiveRecord屬性

class Profile < ActiveRecord::Base 
    attr_accessor :tmp_postal_code 

    def postal_code=(postal_code) 
    @temp_postal_code = postal_code[:first] + "-" + postal_code[:second] 
    end 

    def postal_code 
    @temp_postal_code 
    end 
end 

我第一改寫postal_code=(postal_code)因爲params在控制器是散列例如,({:first => "1234", :second => "9999"})。其次,當我嘗試使用getter方法時,我得到了零,所以我添加了getter方法。爲了分享postal_code屬性的值,我製作了@temp_postal_code

現在一切工作除了一個。看看下面的控制檯輸出。

>> p = Profile.new 
    SQL (0.1ms) SET NAMES 'utf8' 
    SQL (0.1ms) SET SQL_AUTO_IS_NULL=0 
    Profile Columns (1.3ms) SHOW FIELDS FROM `profiles` 
=> #<Profile id: nil, name: nil, pr: "", age: nil, postal_code: nil> 
>> p.postal_code = {:first => "123", :second => "9999"} 
=> {:second=>"9999", :first=>"123"} 
>> p.postal_code 
=> "123-9999" 
>> p.postal_code 
=> "123-9999" 
>> p.name = "TK" 
=> "TK" 
>> p.postal_code 
=> "123-9999" 
>> p.pr = "Hello" 
=> "Hello" 
>> p.age = 20 
=> 20 
>> p 
=> #<Profile id: nil, name: "TK", pr: "Hello", age: 20, postal_code: nil> # WHY!!! 
>> p.postal_code 
=> "123-9999" 

當我試圖通過p.postal_code訪問單獨postal_code屬性,存在的價值。但是當我嘗試顯示p時,postal_codenil。它看起來像後者用於save操作。我無法將郵政編碼保存爲有意義的值。

我對虛擬屬性的理解和屬性的覆蓋有些不對。通過進一步的探索,我發現了散列符號和點符號之間的區別。

>> p[:postal_code] 
    => nil 
    >> p[:name] 
    => "TK" 
    >> p.postal_code 
    => "123-9999" 

我不知道爲什麼會出現這種情況。我希望能夠savepostal_code填寫。

回答

0

您想要使用super方法,以便它實際上被放入AR屬性。

def postal_code=(postal_code) 
    super(postal_code[:first] + "-" + postal_code[:second]) 
    end 

    # you shouldn't even need this anymore 
    def postal_code 
    @temp_postal_code 
    end 

你不會再需要attr_accessor。希望有所幫助。

+0

非常感謝。現在一切工作文件。 – 2009-12-24 16:12:48