Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Gem Development - How to use ActiveRecord?

I'm currently trying to develop my first ruby gem and I'm already stuck. I used the "bundle gem" command to create the basic structure and read some tutorials but what I can't find is how to integrate ActiveRecord.

Where do I create my migrations?

Do I create the "db/migrations" folder within the lib folder or at the root?

And do I have to do anything in the Rakefile (I found some questions where the answer was something like "you have to create your own [my_gem]:db:migrate" or something like that.)

All I need is a way to create a gem, which defines ActiveRecord models (including the migrations of course), which can then be used by a rails app.

Any help on that one would be greatly appreciated!

Greetings, Flo

like image 515
LetzFlow Avatar asked Aug 04 '11 08:08

LetzFlow


People also ask

What is Ruby gem ActiveRecord?

ActiveRecord is a gem that is part of Ruby on Rails. It is the ORM, i.e. the library that maps our objects to tables. In other words, it is the Ruby library that allows us to use Ruby classes in order to access our data stored in an RDBMS, like MySQL or PostgreSQL.

What does ActiveRecord base do?

Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work.

Can you use ActiveRecord without Rails?

ActiveRecord is commonly used with the Ruby-on-Rails framework but you can use it with Sinatra or without any web framework if desired.

What is ActiveRecord?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

When building a gem to integrate with a rails project, you want to build a railtie engine. If you are using rails 3.0.x, use enginex, if you are using rails 3.1 you should be use the new generator:

rails g plugin new your-plugin-name

Then, inside your gem, you can just define models, inside the app/models/ folder and they will automatically be picked up.

Migrations is somewhat harder: for rails 3.1 it is ok if you define them in the correct folder, in rails 3.0 you will have to manually generate a task to copy the migrations to your code-base. Check this link where I answered that very question.

For more information on rails engines check this and this article.

like image 74
nathanvda Avatar answered Sep 28 '22 13:09

nathanvda