2011-06-13 4 views
3

레일즈 3에는 데이터베이스가 아닌 모든 모델에 유효성 검사를 추가하기위한 ActiveRecord 모듈이 포함됩니다. 양식 (예 : ContactForm 모델)에 대한 모델을 만들고 ActiveRecord 평가를 포함하고 싶습니다. 그러나 Rails 2.3.11에는 ActiveRecord 모듈을 포함시킬 수 없습니다. 레일즈 2.3.11에서 레일스 3와 동일한 동작을 수행 할 수있는 방법이 있습니까?레일 2.3.11 폼용 모델 생성 및 ActiveRecord 유효성 검사

답변

2

하나 이상의 모델에 대한 유효성 검사 프록시의 일종으로 가상 클래스를 사용하려는 경우 다음이 도움이 될 수 있습니다 (2.3.x의 경우 3.xx를 사용하면 앞에서 설명한 ActiveModel을 사용할 수 있음).

class Registration 
    attr_accessor :profile, :other_ar_model, :unencrypted_pass, :unencrypted_pass_confirmation, :new_email 
    attr_accessor :errors 

    def initialize(*args) 
    # Create an Errors object, which is required by validations and to use some view methods. 
    @errors = ActiveRecord::Errors.new(self) 
    end 

    def save 
    profile.save 
    other_ar_model.save 
    end 
    def save! 
    profile.save! 
    other_ar_model.save! 
    end 

    def new_record? 
    false 
    end 

    def update_attribute 
    end 
    include ActiveRecord::Validations 
    validates_format_of :new_email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i 
    validates_presence_of :unencrypted_pass 
    validates_confirmation_of :unencrypted_pass 
end 

이 방법 당신은 당신이 그들을 정의하기 전에 그것을 포함하려고하면 savesave! 방법을 사용할 수없는 것을 불평 유효성 검증 서브 모듈을 포함 할 수 있습니다. 아마도 최선의 해결책은 아니지만 작동합니다.

관련 문제