2009-12-24 4 views
0

액티브 레코드 파일에 다음 코드가 있습니다. 제어기에 params 해시 예컨대 때문에액티브 레코드 속성

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 

나는 제 ({:first => "1234", :second => "9999"}) postal_code=(postal_code)을 덮어. 둘째, getter 메서드를 사용하려고 시도했을 때 nil을 얻었으므로 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 작동에 사용 된 것처럼 보입니다. 의미있는 가치로 우편 번호를 저장할 수 없습니다.

가상 속성 및 속성 덮어 쓰기에 대한 저의 이해가 잘못되었습니다. 추가 탐구를 통해 해시 표기법과 점 표기법의 차이점을 발견했습니다.

왜 이런 일이 발생하는지는 잘 모릅니다. 나는 postal_code으로 save을 채울 수 있기를 원합니다.

답변

0

슈퍼 메서드를 사용하여 실제로 AR 특성에 넣을 수 있습니다.

더 이상 attr_accessor가 필요하지 않습니다. 희망이 도움이됩니다.

+0

고마워요. 이제는 모든 것이 작동합니다. –

관련 문제