Web & Mobile app development boutique | VAIRIX

ActiveModel Rails 4


ActiveModel has different modules that can be mixin in your class to add behavior.


To add validations to your class you only need to mixin the module ActiveModel::Validations
Notice the new validatior, absence of.

  class Person
    include ActiveModel::Validations

    attr_accessor :first_name
    attr_accessor :signature

    validates :first_name, presence: true
    validates :signature, absence: true



If you need more active record behavior in your class than just validation you can mixin the ActiveModel::Model module, which will allow ruby objects to work with ActionPack and use instances of that class in view helpers such as form_for. It will also give more features to your classes such as:

  • Model name introspections
  • Conversions
  • Traslations
  • Validations


  Class Contact
    include ActiveModel::Model

    attr_accessor :name, :email, :message

    validates :name, presence: true
    validates :email, presence: true
    validates :message, presence: true, length: { maximim: 100 }


  <%= form_for @contact do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name %>

    <%= f.label :email %>
    <%= f.email_field :email %>

    <%= f.label :message %>
    <%= f.text_area :message %>

    <%= f.submit 'Submit' %>
  <% end %>




By Pablo Monfort


Check out our News page: