Rodrigo Urubatan – About Code

Helping ruby developers to use the best tools for each job so they can solve hard problems, with less bugs and have more free time.

Menu
  • Home
  • My last presentations
  • About
  • Privacy Policy
Menu

Simple and easy way to use ActiveRecord without Rails

Posted on May 21, 2019May 17, 2019 by urubatan

After a question in my other post about how to use sidekiq without rails, I decided to also post here how to use ActiveRecord without Rails

But Just to simplify things a lot, I’ll show how to do it using only one file, then you can split it up in your projects.

require 'active_record'
ActiveRecord::Base.establish_connection({adapter: :sqlite3, database: 'test.db'})
 
 
 
class CreateTestModel < ActiveRecord::Migration[5.1]
  def change
    create_table :test_models do |t|
      t.string :name
    end
  end
end
 
CreateTestModel.migrate :up
 
class TestModel < ActiveRecord::Base
end
 
TestModel.create(name: 'First Test')
TestModel.create(name: 'Second Test')

As you can see, what you need is pretty simple, you just need to:

  • load the ‘active_record’ gem
  • establish the connection passing a hash with the configuration
  • running your migrations
  • creating your model classes
  • And using your models as you would normally in a Rails application

But how can we improve that?

You can merge this with the standalone sidekiq sample from the other post, split the files in their own directory instead of using only one file for everything, and just be happy loading only the gems you need!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit
  • Pocket
  • WhatsApp

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Receive the latest posts by email!

Last posts

  • ActiveRecord Migration UI gem
  • Beware of Date.yesterday on your code (A timezone history)
  • How to create a request scope for your rails application
  • Random collection of Git Tips and Tricks
  • 6 Lessons From CrossFit That will help your developer career (Or any other career in the matter of fact)

Search

© 2019 Rodrigo Urubatan – About Code | Powered by Minimalist Blog WordPress Theme