A Good ORM Will Handle Most of Your Needs
An ORM tool can handle many of the repetitive processes when interfacing with a database. Your project might call for an ORM tool, such as ActiveRecord. No doubt about it, a good ORM can come in handy. An ORM application will typically have a function for passing in raw SQL if needed, so you may not need to go straight to the driver.
Why Learn to Use the Driver Directly?
An ORM brings its own, different complexity to a project. It may be overkill for some projects. There are also times when a specific task is just different enough that an ORM may not be able to help, or its application to your requirements become so complex that your code becomes difficult to maintain.
And if you're like me, it's hard to be satisfied with a black box approach. You want to know more about how your tools work and you want to have options, just in case.
When you have enough knowledge to implement direct CRUD operations, you are in a better position to choose the right tool for the right job.
All examples in this series will use the same database objects and connection information.
Creating the Database Objects
The following can be used to setup the initial tables we'll use. Please make sure you're connected to a schema in which you can safely execute commands like these.
CREATE TABLE LCS_PEOPLE ( id NUMBER GENERATED BY DEFAULT AS identity, name VARCHAR2(20), age NUMBER, notes VARCHAR2(100) ) / ALTER TABLE LCS_PEOPLE ADD CONSTRAINT PK_LCS_PEOPLE PRIMARY KEY ("ID") / CREATE TABLE LCS_PETS ( id NUMBER GENERATED BY DEFAULT AS IDENTITY, name VARCHAR2(20), owner NUMBER, type VARCHAR2(100) ) / ALTER TABLE LCS_PETS ADD CONSTRAINT PK_LCS_PETS PRIMARY KEY ("ID") / ALTER TABLE LCS_PETS ADD CONSTRAINT FK_LCS_PETS_OWNER FOREIGN KEY ("OWNER") REFERENCES "LCS_PEOPLE" ("ID") / INSERT INTO LCS_PEOPLE (name, age, notes) VALUES ('Bob', 35, 'I like dogs') / INSERT INTO LCS_PEOPLE (name, age, notes) VALUES ('Kim', 27, 'I like birds') / INSERT INTO LCS_PETS (name, owner, type) VALUES ('Duke', 1, 'dog') / INSERT INTO LCS_PETS (name, owner, type) VALUES ('Pepe', 2, 'bird') / COMMIT /
Making the Connection
- You'll need the ruby-oci8 driver.
- Get the connection string from the environment variable.
- Create the connection object.
require 'oci8' connectString = ENV['db_connect'] con = OCI8.new(connectString)
We will include this code section with all examples and use the "con" connection object "con" throughout the series.
To clean up the database when you are finished with the series, you just need to drop the two tables. Please make sure you're connected to the correct schema where you created the tables.
drop table LCS_PETS / drop table LCS_PEOPLE /
Guide to Ruby-OCI8 CRUD Series
Create records (Coming soon)
Update records (Coming soon)
Delete records (Coming soon)