Non persistent rails model

One of the most appreciated aspects of most of the modern framework, is the ActiveRecord: through this tool you can very easily manage the data through many functions such as the ability to manage a database in an almost automated way or performs syntax checks on the data entered.
These days, though, I had the need to structure a model in Rails where all inserted data does not need to be persistent and therefore must “die” once used; to do this, it would simply create a new class that doesn’t inherits the class ActiveRecord::Base, however, by doing so, you lose the functionality of automatic form contol.
I have discarded the idea of creating an ActiveRecord model without fields and with only attributes “attr_accessor”, because it still creates an empty table in the DB and, for cleaning, it is a thing I do not like.
Here’s how I did it.
First of all, I created a new model called “EphemeralModel” that inherits ActiveRecord::Base

EphemeralModelSource Article
1
2
3
4
5
6
class EphemeralModel < ActiveRecord::Base
    def self.columns() @columns ||= []; end
    def self.column(name, sql_type = nil, default = nil, null = true)
        columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
    end
end

At this point you can use the new class as the basis for our model non-persistent

NonPersistentEmail
1
2
3
4
class NonPersistentEmail < EphemeralModel
   column :email, :string
   validates_format_of :email, :with => /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/
end

The class NonPersistentEmail is an ActiveModel class to all effects, for which we can use them with the function “form_for”, or (as in the example) add a validation … only that data entered into the form will be used only for processing and will not be saved in the database.