ActiveRecord without Rails
Simple guide on how to use ActiveRecord without Rails
I am a big fun of ActiveRecord and recently I was experimenting with it on my free time. On this post I am going to show a very simple way on how to use it without having installed Rails.
I have used the following folder structure for the example app:
What we have to do is just to include activerecord gem inside our Gemfile and then bundle install
in the terminal. For this example we are going to use the sqlite3 adapter.
Gemfile:
Then we are going to write a migration under the db/migrate/
folder and the corresponding model under the models/
folder.
Notice the 001 on the migration’s filename, is used for the order the migrations are being executed.
db/migrate/001_create_users.rb:
models/user.rb
Three more things to be done and we are ready. First we need a rake task to execute the migrations (Rakefile), secondly a configuration file for the database (database.yml) and lastly an application setup file (app.rb).
Rakefile
config/database.yml
app.rb
That’s it! Now we can run the migration as we normally do for a Rails app, rake db:migrate
and we are ready.
Play time!
Fire up irb or pry in the terminal and require the app.rb file (require './app'
). Now we are ready to use ActiveRecord without having rails. I definitely recommend the api.rubyonrails.org and http://guides.rubyonrails.org for more information, I found them extremely useful.
Hope you find this post helpful enough for very basic usage of ActiveRecord without Rails. 😀