Coder Social home page Coder Social logo

active-record-mechanics-crud's Introduction

Active Record Mechanics (CRUD)

Objectives

  1. Understand the connection between an ORM and Active Record
  2. Understand why Active Record is useful
  3. Develop a basic understanding of how to get started with Active Record

ORM vs Active Record

By now you are familiar with the concept of an ORM, an Object-Relation Mapper, and should have written something of your own in the Student and InteractiveRecord classes. Our latest iteration was our most powerful yet, it could give us lots of functionality via inheritance.

While building your own ORM for a single Class is a great way to learn about how object-oriented programming languages commonly interact with a database, imagine you had many more classes. To test and maintain custom code for each project we work on would distract our attention from making cool stuff to building database connectivity. To save themselves and other developers this headache, the ActiveRecord Ruby gem team built the ActiveRecord gem.

In this lesson we'll read about how to to have ActiveRecord link our Ruby models with rows in a database table. We won't write the code yet, but we'll familiarize ourself with common code blocs used in ActiveRecord-using projects.

Active Record ORM

Active Record is a Ruby gem, meaning we get an entire library of code just by running gem install activerecord or by including it in our Gemfile.

Connect to DB

Once our Gem environment knows to put ActiveRecord into the picture, we need to tell ActiveRecord where the database is located that it will be working with.

We do this by running ActiveRecord::Base.establish_connection. Once establish_connection is run, ActiveRecord::Base keeps it stored as a class variable at ActiveRecord::Base.connection.

NOTE: If you'd like to type along in an IDE environment, you can experiment by using IRB with: irb -r active_record provided you've installed ActiveRecord with gem install activerecord

ActiveRecord::Base.establish_connection(
  :adapter => "sqlite3",
  :database => "db/students.sqlite"
)

Create a table

But our database is empty. Let's create a table to hold students.

Let's create our table using SQL:

sql = <<-SQL
  CREATE TABLE IF NOT EXISTS students (
  id INTEGER PRIMARY KEY,
  name TEXT
  )
SQL

# Remember, the previous step has to run first so that `connection` is set!
ActiveRecord::Base.connection.execute(sql)

Link a Student "model" to the database table students

The last step is to tell your Ruby class to make use of ActiveRecord's built-in ORM methods. With Active Record and other ORMs, this is managed through Class Inheritance. We simply make our class (Student) a subclass of ActiveRecord::Base.

class Student < ActiveRecord::Base
end

Our Student class is now our gateway for talking to the students table in the database. The Student class has gained a whole bunch of new methods via its inheritance relationship to ActiveRecord. Let's look at a few of them

.column_names

Retrieve a list of all the columns in the table:

Student.column_names
#=> [:id, :name]
.create

Create a new Student entry in the database:

Student.create(name: 'Jon')
# INSERT INTO students (name) VALUES ('Jon')
.find

Retrieve a Student from the database by id:

Student.find(1)
.find_by

Find by any attribute, such as name:

Student.find_by(name: 'Jon')
# SELECT * FROM students WHERE (name = 'Jon') LIMIT 1
attr_accessors

You can get or set attributes of an instance of Student once you've retrieved it:

student = Student.find_by(name: 'Jon')
student.name
#=> 'Jon'

student.name = 'Steve'

student.name
#=> 'Steve'
#save

And then save those changes to the database:

student = Student.find_by(name: 'Jon')
student.name = 'Steve'
student.save

Note that our Student class doesn't have any methods defined for #name either. Nor does it make use of Ruby's built-in attr_accessor method.

class Student < ActiveRecord::Base
end

Conclusion

You've now seen how ActiveRecord creates a link between Ruby and databases.

View Active Record Mechanics (CRUD) on Learn.co and start learning to code for free.

active-record-mechanics-crud's People

Contributors

annjohn avatar drakeltheryuujin avatar franknowinski avatar gj avatar joshuabamboo avatar maxwellbenton avatar sgharms avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-record-mechanics-crud's Issues

Add additional info

Hi, I finished reading this page, and went on trying to work on the Mechanics of Migration lab.

Can you add information in this read me AND in the Mechanics of Migration lab on where to add code to connect to DB and creating table using sql? I ended up having to skip some of the SQL lessons and went to Active Record lessons first. Not sure if this information is already obvious through the SQL lessons but can you add info about where to add the following code? The current instructions simply say, "This is how we would connect to a database" and "Let's create our table using SQL:" but it doesn't tell us exactly where the code should be. I think it would be a great help for future students as well. Thanks.

connection = ActiveRecord::Base.establish_connection(
  :adapter => "sqlite3",
  :database => "db/students.sqlite"
)

and

sql = <<-SQL
  CREATE TABLE IF NOT EXISTS students (
  id INTEGER PRIMARY KEY, 
  name TEXT
  )
SQL
 
ActiveRecord::Base.connection.execute(sql)

Grammar mistake on first sentence.

BY NOW YOU BE FAMILIAR with the concept of an ORM, an Object-Relation Mapper, and should have written something of your own in the Student and InteractiveRecord classes.

think not Think

Need a lower-case T in the middle of this sentence:
"And as a result, Active Record gives you enormous functionality (Think of our ORM with a lot more methods)."

Thank you.

Small Grammar Errors "You Be..."

Hi there.
First line's verb should be "By now you ARE familiar..."


"ORM vs Active Record
By now you be familiar with the concept of an ORM, an Object-Relation Mapper, and should have written something of your own in the Student and InteractiveRecord classes. Our latest iteration was our most powerful yet, it could give us lots of functionality via inheritance."

inconsistency in the included examples

A table is created called students. Afterwards the examples mix in instances of songs and artists. There is no uniformity. Here is the example that was used to describe the .find_by method:
Student.find_by(name: 'Jon')

SELECT * FROM artists WHERE (name = 'Jon') LIMIT 1

Intro to rake lab

The rake file lab has a part where we run the statement rake greeting:hello from the terminal. Doing so causes an error for me. At first it was a bundle install thing. Did that and still an error posts. The error rake aborted! Don't know how to build task 'greeting:hello' (see --tasks)

ATURKEWI SAID 2 MINUTES AGO
Hey Richard!

ATURKEWI SAID 2 MINUTES AGO
So it looks like we need to update this lab a little bit.

ATURKEWI SAID A MINUTE AGO
You can see a list of all possible rake tasks if you run rake -T

ATURKEWI SAID A MINUTE AGO
## And we can see there is no rake greeting:hello
RNHUTSKO SAID A MINUTE AGO
yep. That is it.

ATURKEWI SAID A MINUTE AGO
There is just rake hello

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.