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