How to Play with Rails ActiveModel in IRB

Install the gem.

gem install activemodel

Create a contact class and mixin ActiveModel.

require 'active_model'

class Contact
  include ActiveModel::Model

  attr_accessor :name

  validates :name, presence: true
end

We gave defined a name attribute with a validation for it. We can now experiment in the IRB console:

 $ irb
 load './contact.rb'
 c = Contact.new
 c.valid?
 # => false

We need a name for a valid contact object.

bugs = Contact.new(name: 'Bugs Bunny')
bugs.valid?
 => true 

The invalid contact has no name.

c.name
 => nil 

The valid contact has a name.

bugs.name
 => "Bugs Bunny" 

If you don't provide:

attr_accessor :name

you will get:

NoMethodError: undefined method `name=' for #<Contact:0x004a70>

when you instantiate the object.

bugs = Contact.new(name: 'Bugs Bunny')

References

Active Model Rails 4
Document Structure Resource Collection Representations


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.