我在ActiveRecord上有以下模型类。如何为这个类编写一个等效的ActiveModel?
class Recommendation < ActiveRecord::Base
def self.columns() @columns ||= []; end
def self.column(name, sql_type = nil, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
column :from_email, :string
column :to_email, :string
column :article_id, :integer
column :message, :text
serialize :exception
validates_format_of :from_email, :to_email, :with => /^[-a-z0-9_+.]+@([-a-z0-9]+.)+[a-z0-9]{2,4}$/i
validates_length_of :message, :maximum => 500
belongs_to :article
end
我建议您从一个普通类开始,然后开始添加ActiveModel模块。比如说,从验证开始。
http://api.rubyonrails.org/classes/ActiveModel/Validations.html
class Recommendation
include ActiveModel::Validations
attr_accessor :from_email, :to_email, :article_id, :message
validates_format_of :from_email, :to_email, :with => /^[-a-z0-9_+.]+@([-a-z0-9]+.)+[a-z0-9]{2,4}$/i
validates_length_of :message, :maximum => 500
end
其他ActiveModel文档可以在http://api.rubyonrails.org/