Rails 3 では、データベースを使用しないモデルに検証を追加するために、ActiveRecord モジュールを含めるだけです。フォームのモデル (ContactForm モデルなど) を作成し、ActiveRecord の検証を含めたいと考えています。ただし、Rails 2.3.11 に ActiveRecord モジュールを単純に含めることはできません。Rails 2.3.11 で Rails 3 と同じ動作を実現する方法はありますか?
1 に答える
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
このようにして、Validationsサブモジュールを含めることができます。これは、メソッドを定義する前にインクルードしようとするsaveと、save!メソッドが使用できないことを通知します。おそらく最善の解決策ではありませんが、機能します。
于 2011-07-19T15:21:30.257 に答える