ActiveModel in Rails3

In Rails3 Active Model feature is added that helps to use feature of active record class for a non active record class.In Active Model you can make Any Ruby Object Feel Like Active Record and can get Rails-style models with validations, serialization, callbacks, dirty tracking, internationalization, attributes, observers and all the other Rails goodness.

Here is the example –:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Message
  include ActiveModel::Validations
  include ActiveModel::Conversion
  include ActiveModel::Naming

  attr_accessor :name,:email,:text_message

  validates_presence_of :name
  validates_presence_of :email
  validates_presence_of :text_message
  validates_length_of :text_message, :maximum => 500

  def initialize(attributes={})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

end
1
2
3
4
5
6
7
8
9
@message = Message.new({:name => "rays", :email => '[email protected]', :text_message => "this my text message"})

@message.valid? => true

@message = Message.new({:name => "rays", :text_message => "this my text message"})

@message.valid? => false

@message.errors will give error "Email can't be blank"