Here's some thoughts which might help clarify it for you. I'm more familiar with ActiveRecord than Sequelize, so I'll run with that, but the concepts should be the same for both.
You have a database. You can, completely independent of Rails (eg. using a database admin tool), go and run a query on that database - something like "select * from users limit 1"
. But that just gives you a set of results in some admin window, which aren't much use to your Rails app. You want to be able to execute SQL from your Rails app, and get data back in a form that Ruby/Rails can work with. You need to Access
your Data
through some kind of ruby Object
- you need a Data Access Object
, or DAO
.
In rails, you could run the query above with something like:
result = ActiveRecord::Base.connection.execute("select * from users limit 1")
The result
variable won't know or care about your User
model. All it will contain is essentially a list of plain ruby Hash
instances, like:
{
"id" => "1234",
"email" => "fred@example.com",
"first_name" => "Fred",
"last_name" => "Flintstone",
}
If you wanted to update the first_name
to Bob
, you couldn't just edit that hash and call save on it - it's just a plain old hash, just the data and no extra smarts. So you'd have to write your own SQL again, and get Rails to execute it for you:
ActiveRecord::Base.connection.execute("update users set first_name = 'Bob' where id = 1234")
So what you're using in this context is basically just Rail's DAO
, without using it's ORM
.
The ORM
is like a layer on top of the DAO
. You can have a DAO
without an ORM
, but you can't have an ORM
without a DAO
. The ORM
, or Object Relational Mapper
will Map
concepts / records in your Relational
database with Objects
in your programming language (ie, Ruby). So, if you wanted to do the stuff above, using Rail's ORM
rather than using it's DAO
, it might look like:
user = User.find(1234)
user.name = 'Bob'
user.save!
See how much nicer it is using an ORM? Now, the snippet above, using the ORM, will still essentially just execute the same SQL we detailed earlier. The ORM just abstracts away more of the details and provides smarter objects to save us a bunch of extra work.
Again, the concepts demonstrated are transferable to Sequelize / Javascript and other langs/frameworks.
So a DAO
is just "an object that can execute SQL and return results in some basic data structure native to the programming language". An ORM
will ultimately use a DAO
to communicate with the database, but provides a whole lot more on top.