Isnor Creative
Isnor Creative Blog
Ruby, Ruby on Rails, Ember, Elm, Phoenix, Elixir, React, Vue

May 8, 2014

Easier Non ActiveRecord models in Rails 4

Rails 4 introduces a nice new feature for dealing with non-ActiveRecord models. These kinds of models can be useful in a situation where you have a class that you want to function like a typical ActiveRecord model, but you have no need to persist it to the database. I’ve done this on a few occasions with contact forms, for example.

Where previously you might have set up a model that looked something like this, with active model pieces being brought in to the class individually, a class constructor to set up attributes, as well as some random methods required to make it work, the persisted? method shown below, for example:

class Contact
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attr_accessor :email, :message

  validates :email, presence: true, length: {in:2..255}

  def initialize(attributes = {})
    self.attributes = attributes
  end

  def attributes=(attributes)
    @email = attributes[:email]
    @message = attributes[:message]
  end
  private :def_attributes

  def persisted?
    false
  end

end

Rails 4 introduces ActiveModel::Model, which could clean up the above class to look something like this:

class Contact
  include ActiveModel::Model

  attr_accessor :email, :message

  validates :email, presence: true, length: {in:2..255}

end

In this example, the class constructor which was being used to initialze the object with an attribute hash been removed; the persisted? method is no longer necessary; the various ActiveModel includes have been reduced to a one-liner. Depending on what bits you’ve needed from ActiveModel, it may have other benefits.


I am available for Ruby on Rails consulting work – get in touch to learn more.

Gordon B. Isnor

Gordon B. Isnor writes about Ruby on Rails, Ember.js, Elm, Elixir, Phoenix, React, Vue and the web.
If you enjoyed this article, you may be interested in the occasional newsletter.

I am now available for project work. I have availability to build greenfield sites and applications, to maintain and update/upgrade existing applications, team augmentation. I offer website/web application assessment packages that can help with SEO/security/performance/accessibility and best practices. Let’s talk

comments powered by Disqus