Cách tiếp cận tốt nhất là kết thúc mô hình giả của bạn trong một lớp và thêm các xác thực vào đó. Cách Rails nói rằng bạn không nên đặt hành vi mô hình trên các bộ điều khiển, các xác nhận hợp lệ duy nhất phải là các hành động yêu cầu (xác thực, ủy quyền, v.v.)
Trong Rails 2.3+, bạn có thể bao gồm ActiveRecord::Validations
, với một nhược điểm nhỏ là bạn phải định nghĩa một số phương thức mà lớp ActiveRecord mong đợi. Xem this post để có giải thích sâu hơn. Mã dưới đây chuyển thể từ bài rằng:
require 'active_record/validations'
class Email
attr_accessor :name, :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
# Required method stubs
def save
end
def save!
end
def new_record?
false
end
def update_attribute
end
# Mix in that validation goodness!
include ActiveRecord::Validations
# Validations! =)
validates_presence_of :name
validates_format_of :email, :with => SOME_EMAIL_REGEXP
end
Trong Rails3, bạn có những sexy validations theo ý của bạn :)
vị ngọt !!!!!!! – denniss
Dễ như bánh. Cảm ơn bạn, nơi tìm kiếm một cái gì đó như thế này. –
Đối với Rails 3, thay thế ActiveRecord :: Lỗi với ActiveModel :: Errors –