Rails model without database
Asked Answered
T

13

76

I want to create a Rails (2.1 and 2.2) model with ActiveRecord validations, but without a database table. What is the most widely used approach? I've found some plugins that claim to offer this functionality, but many of them don't appear to be widely used or maintained. What does the community recommend I do? Right now I am leaning toward coming up with my own solution based on this blog post.

Toboggan answered 24/11, 2008 at 23:18 Comment(4)
The blog post linked is now dead.Sylvanite
prestonlee.com/2007/12/29/… and yet alive under a new name.Affront
web.archive.org/web/20100716123520/http://www.prestonlee.com/… because it seems to be down againIndubitable
This seems to be a duplicate of #937929 which actually proposes a better solution.Shapely
E
9

I think the blog post you are linking is the best way to go. I would only suggest moving the stubbed out methods into a module not to pollute your code.

Explicit answered 25/11, 2008 at 15:20 Comment(3)
I'm with Honza and I think that post is your only option if you need AR's validations in your POCO's. Good luck.Gaskill
The post is missing when I visited could you post it here ?Yeryerevan
Rails introduced ActiveModel as their way of solving this problem - there is an answer covering this below https://mcmap.net/q/265861/-rails-model-without-databaseAnnoy
M
71

There is a better way to do this in Rails 3: http://railscasts.com/episodes/219-active-model

Masturbate answered 30/9, 2010 at 13:29 Comment(2)
I voted you up because I agree this is a cleaner and better way to do it especially if starting a new project. However, I did find John Topley's solution to be better on a project where lots of code still needs to think your model is a subclass of ActiveRecord::Base. One specific example of this method not easily working is if your code relies on a 3rd party plugin that relies on ActiveRecord.Manumit
In Rails 4 there is also ActiveModel::Model, which includes many of the ActiveModel modules and some other magic, to make you feel your (non-persisted or custom-persisted) model like an ActiveRecord model.Disarming
C
41

This is an approach I have used in the past:

In app/models/tableless.rb

class Tableless < 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

  # Override the save method to prevent exceptions.
  def save(validate = true)
    validate ? valid? : true
  end
end

In app/models/foo.rb

class Foo < Tableless
  column :bar, :string  
  validates_presence_of :bar
end

In script/console

Loading development environment (Rails 2.2.2)
>> foo = Foo.new
=> #<Foo bar: nil>
>> foo.valid?
=> false
>> foo.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>>
Curnin answered 25/11, 2008 at 21:22 Comment(5)
Works well and very lightweight. Rails 2.3 will complain a bit about the lack of a table at script/console, but adding "self.abstract_class = true" solves that (without preventing instantiation).Dimissory
This seems hideous to me. Why bother inheriting from ActiveRecord::Base if you don't want a database back-end? There are other libraries that provide validation functionality that don't assume a database backend.Dropping
@Trona See #3416984Dropping
@David. Ok, that's one. Any others?Trona
Just for record: first option (#3416984) is for Rails 3 only.Scarificator
A
30

There is easier way now:

class Model
  include ActiveModel::Model

  attr_accessor :var

  validates :var, presence: true
end

ActiveModel::Model code:

module ActiveModel
  module Model
    def self.included(base)
      base.class_eval do
        extend  ActiveModel::Naming
        extend  ActiveModel::Translation
        include ActiveModel::Validations
        include ActiveModel::Conversion
      end
    end

    def initialize(params={})
      params.each do |attr, value|
        self.public_send("#{attr}=", value)
      end if params
    end

    def persisted?
      false
    end
  end
end

http://api.rubyonrails.org/classes/ActiveModel/Model.html

Apfelstadt answered 18/12, 2015 at 11:45 Comment(1)
This is the way to go nowIndira
E
9

I think the blog post you are linking is the best way to go. I would only suggest moving the stubbed out methods into a module not to pollute your code.

Explicit answered 25/11, 2008 at 15:20 Comment(3)
I'm with Honza and I think that post is your only option if you need AR's validations in your POCO's. Good luck.Gaskill
The post is missing when I visited could you post it here ?Yeryerevan
Rails introduced ActiveModel as their way of solving this problem - there is an answer covering this below https://mcmap.net/q/265861/-rails-model-without-databaseAnnoy
C
7

just create a new file ending in ".rb" following the conventions you're used to (singular for file name and class name, underscored for file name, camel case for class name) on your "models/" directory. The key here is to not inherit your model from ActiveRecord (because it is AR that gives you the database functionality). e.g.: for a new model for cars, create a file called "car.rb" in your models/ directory and inside your model:

class Car
    # here goes all your model's stuff
end

edit: btw, if you want attributes on your class, you can use here everything you use on ruby, just add a couple lines using "attr_accessor":

class Car
    attr_accessor :wheels # this will create for you the reader and writer for this attribute
    attr_accessor :doors # ya, this will do the same

    # here goes all your model's stuff
end

edit #2: after reading Mike's comment, I'd tell you to go his way if you want all of the ActiveRecord's functionality but no table on the database. If you just want an ordinary Ruby class, maybe you'll find this solution better ;)

Clere answered 25/11, 2008 at 1:14 Comment(2)
but this doesn't give him the AR validations.Gaskill
good point. i bet there's a lot of use cases for both solutions :)Clere
D
5

For the sake of completeness:

Rails now (at V5) has a handy module you can include:

include ActiveModel::Model

This allows you to initialise with a hash, and use validations amongst other things.

Full documentation is here.

Drily answered 30/6, 2017 at 14:48 Comment(0)
O
4

There's a screencast about non-Active Record model, made up by Ryan Bates. A good place to start from.

Just in case you did not already watch it.

Oscular answered 25/11, 2008 at 15:23 Comment(2)
again this doesn't solve the posters problem of using AR's validations.Gaskill
I followed these instructions in my app, and it worked perfectly.Geographer
T
4

I have built a quick Mixin to handle this, as per John Topley's suggestion.

http://github.com/willrjmarshall/Tableless

Tabanid answered 18/6, 2010 at 3:51 Comment(0)
G
2

What about marking the class as abstract?

class Car < ActiveRecord::Base
  self.abstract = true
end

this will tell rails that the Car class has no corresponding table.

[edit]

this won't really help you if you'll need to do something like:

my_car = Car.new
Gaskill answered 25/11, 2008 at 1:18 Comment(0)
I
2

Use the Validatable gem. As you say, there are AR-based solutions, but they tend to be brittle.

http://validatable.rubyforge.org/

Isocyanide answered 12/5, 2009 at 3:52 Comment(0)
O
1

Anybody has ever tried to include ActiveRecord::Validations and ActiveRecord::Validations::ClassMethods in a non-Active Record class and see what happens when trying to setup validators ?

I'm sure there are plenty of dependencies between the validation framework and ActiveRecord itself. But you may succeed in getting rid of those dependencies by forking your own validation framework from the AR validation framework.

Just an idea.

Update: oopps, this is more or less what's suggested in the post linked with your question. Sorry for the disturbance.

Oscular answered 26/11, 2008 at 10:21 Comment(1)
Your answer is useful now because the blog post no longer exists.Wotan
I
0

Do like Tiago Pinto said and just don't have your model inherit from ActiveRecord::Base. It'll just be a regular Ruby class that you stick in a file in your app/models/ directory. If none of your models have tables and you're not using a database or ActiveRecord at all in your app, be sure to modify your environment.rb file to have the following line:

config.frameworks -= [:active_record]

This should be within the Rails::Initializer.run do |config| block.

Imray answered 25/11, 2008 at 16:24 Comment(1)
just like Tiago Pinto's answer this won't help our friend use the AR validations in his class.Gaskill
R
0

You ought to checkout the PassiveRecord plugin. It gives you an ActiveRecord-like interface for non-database models. It's simple, and less hassle than fighting ActiveRecord.

We're using PassiveRecord in combination with the Validatable gem to get the OP's desired behaviour.

Reive answered 18/7, 2009 at 4:46 Comment(1)
These days I would probably include ActiveModel and whatever else I needed.Reive

© 2022 - 2024 — McMap. All rights reserved.