Wednesday, April 2

ActiveRecord - CRUD operations -1

Having seen how do we handle the relationships across db tables through rails now let us dig little deeper on how to perform CRUD operations.
Well Rails ActiveRecord does help you out with lots of keywords and many more convenient, easily understandable, meaningful commands. In nut shell, you can carryout all these sql queries without using sql syntax at all...

Inserting data - We generally use SQL Insert statements to insert/create new rows of data and Rails offers a simple way of creating new rows in tables. One of doing it is by using "new" or by "create" method.
The syntax looks very simple, as below:

Based on previous posts we can coolly observe/interpret the above code like this:
  1. As per ActiveRecord pattern in rails, this says that User is the model connecting to users table in database.
  2. All the columns (eg:name here...) of the "users" table go in do ... end loop, 'u' is the iterator.
  3. Once you set the values of each column then end with save (
Why to save?
Because, new method would only creates an object and so to store into db we need to explicitly say it to save.
Is there any alternative one?
In many instances, people create objects, define the data and they tend to forget saving the data. Active Record offers another method, create, which would instantiates the model object as well as stores it into the database.

Using both new, create methods we can either insert multiple rows of data or even the form data can be passed as parameters.

No comments: