1

I am having the following model class on ActiveRecord. How to write an equivalent ActiveModel for this class?

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
Thong Kuah
  • 3,263
  • 2
  • 19
  • 29
Achaius
  • 5,904
  • 21
  • 65
  • 122

1 Answers1

0

I suggest you start with a plain class, and then start adding in ActiveModel modules. Say, start with validation.

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

The other ActiveModel docs can be found at http://api.rubyonrails.org/

Thong Kuah
  • 3,263
  • 2
  • 19
  • 29