2011-09-30 5 views
2

Rails 3 및 ActiveModel을 사용하여 자체를 사용할 수 없습니다. 구문을 사용하여 ActiveModel 기반 개체 내부의 특성 값을 가져옵니다.액세서에 매핑되지 않은 ActiveModel 필드

저장 메소드의 다음 코드에서 self.first_name은 @attributes [: first_name]이 'Firstname'(컨트롤러를 초기화 할 때 전달 된 값)으로 평가되는 nil로 평가됩니다.

ActiveRecord에서 이것은 작동하는 것처럼 보이지만 ActiveModel에서 동일한 클래스를 작성할 때 그렇지 않습니다. ActiveModel 기반 클래스의 접근자를 사용하여 필드를 어떻게 참조합니까?

class Card 
    include ActiveModel::Validations 
    extend ActiveModel::Naming 
    include ActiveModel::Conversion 
    include ActiveModel::Serialization 
    include ActiveModel::Serializers::Xml 

    validates_presence_of :first_name 

    def initialize(attributes = {}) 
    @attributes = attributes 
    end 

    #DWT TODO we need to make sure that the attributes initialize the accessors properyl, and in the same way they would if this was ActiveRecord 
    attr_accessor :attributes, :first_name 

    def read_attribute_for_validation(key) 
    @attributes[key] 
    end 

    #save to the web service 
    def save 
    Rails.logger.info "self vs attribute:\n\t#{self.first_name}\t#{@attributes["first_name"]}" 
    end 

    ... 

end 

답변

3

에 대한 ActiveModel::AttributeMethods이 필요합니다. Marian의 답변에 대한 언급으로 언급 한 "해킹"은 실제로 ActiveRecord 클래스의 접근자가 정확히 생성되는 방법으로 밝혀졌습니다. 여기에 내가했던 일이야 : 당신이 액티브의 소스 코드 (lib/active_record/attribute_methods/{read,write}.rb)에 보면

class MyModel 
    include ActiveModel::AttributeMethods 

    attribute_method_suffix "=" # attr_writers 
    attribute_method_suffix "" # attr_readers 

    define_attribute_methods [:foo, :bar] 

    # ActiveModel expects attributes to be stored in @attributes as a hash 
    attr_reader :attributes 

    private 

    # simulate attribute writers from method_missing 
    def attribute=(attr, value) 
    @attributes[attr] = value 
    end 

    # simulate attribute readers from method_missing 
    def attribute(attr) 
    @attributes[attr] 
    end 
end 

당신은 같은 일을 볼 수 있습니다.

0

당신은 내가 그것을 알아 냈 그

+0

나는 다음을 추가했지만 self.first_name은 아직 평가되지 않습니다'#이 ActiveModel :: AttributeMethods – drsquidop

+0

같은 문제가 해당 페이지로 날 데려 \t # \t #의 define_attribute_methods [ 'FIRST_NAME'] \t #의'를 포함한다. 내 모델에'ActiveModel :: AttributeMethods'를 포함 시켰고 행운이없는'define_attribute_methods'를 호출했습니다. 메서드 접미사를 사용하여 해킹을 시도 할 수 있었지만 ActiveModel이 더 깨끗한 솔루션을 지원할 것으로 기대했습니다. – David

관련 문제