vinod's erudition

we learn everything from failure not from success so keep failing

Home Ruby Rails Javascript Python Agentic AI

Active Records Heart of Ruby on Rails

Posted on April 28, 2014 by vinod

##SQL:

####SQL is language which talks to database

Setup information is stored in specific file called Schema. and this is updated whenever structure of database is changed

####Statements:

####DISTINCT

####GROUP BY

####UPDATE QUERY:

    UPDATE Users 
    SET name='barfoo', email='bar@foo.com' 
    WHERE email='foo@bar.com';`

####JOINS :

Select * from users JOIN posts ON user_id = posts.user_id
SELECT * FROM users JOIN posts ON users.id = posts.user_id WHERE users.id = 42.

####WHERE WONT WORK ON AGGREGATE FUNCTION:

When using aggregate functions like ‘count’ ‘max’ ‘min’ to narrow down the records ‘Where’ wont work here we need to use ‘Having’.

 SELECT users.name, COUNT(posts.*) AS posts_written
    FROM users
    JOIN posts ON users.id = posts.user_id
    GROUP BY users.name
    HAVING posts_written >= 10;

###WHY ACTIVE RECORD ??

####What is ORM ?

So if I want to get an array containing a listing of all the users, instead of writing code to initiate a connection to the database, then doing some sort of SELECT * FROM users query, and converting those results into an array, I can just type User.all and Active Record gives me that array filled with User objects that I can play with as I’d like. Wow!

###Working with Models:

u = User.new({:name => "Sven", :email => "sven@theodinproject.com"})

If you don’t pass a hash, you’ll need to manually add the attributes by setting them like with any other Ruby object: u.name = “Sven”. The second step is to actually save that model instance into the database. Until now, it’s just been sitting in memory and evaporates if you don’t do anything with it. To save, simply call u.save. You can run both steps at once using the #create method:

u = User.create({:name => "Sven", :email => "sven@theodinproject.com"})
This saves you time, but, as you'll see later, you'll sometimes want to separate them in your application.

###MIGRATION :

####Advantages:

###VALIDATION

Validation is nothing but verifying whether right data gets in to database by the authorized people.

###3 Kinds of Validation