ActiveModel Rails 4


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

ActiveModel::Validations


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
  end



ActiveModel::Model


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 }
  end



  <%= 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 %>



References


By Pablo Monfort



How to contact us

Our Location

DireccionArismendi 1420 Of. 102 Telefono(+598) 2409 15 66 Mailinfo@vairix.com

Follow us


Want to contact us?