Showing posts with label activerecord. Show all posts
Showing posts with label activerecord. Show all posts

Wednesday, December 31

Qucik Fix: ActiveRecord Migrations reset_column_information

Few days back I had created few migrations that would rename existing table and again create a table with old name.
  1. user should be renamed as "old_users" 
  2. create a new table "user"
  3. restore the data with different column names in the "user"

  def self.up
    rename_table :users, :old_users
    create_table :users do |t|
      t.column :created_at, :datetime
    end  

    Temp.find(:all).each do |user|
      new_user = User.new(:id=> user.id, :created_at => user.created_at)
      new_user.save!
    end
  end

Don't worry about the Temp, Temp is a class through which I am accessing the old_users table.  Precisely,

class Temp <>
  set_table_name "old_users"
end

This worked pretty well in my local environment and when I deployed in staging, it crashed.  The error was that, it was trying to insert data into table with prvious structure/columns.  Which means, the new structure hasn't taken effective.

The quick fix seems to be reset_column_information.  Before pushing/creating fresh data in the table, I need to reset the column information of the tables.  So including the following line:
      User.reset_column_information
right before creating new users solved the problem.

By the way "WISH YOU HAPPY AND PROSPEROUS NEW YEAR"

Thursday, April 3

ActiveRecord - CRUD operations - 2

We learn t how to create rows in the database. Moving next in CRUD, it is Reading data from db tables. Reading data involves/requires set of constraints/conditions. Something like, details of specific user, product pricing range, sorting order, matching criteria... and the list goes on. To go ahead with these operations ActiveRecord provides the following handy methods, parameter symbols to you:

find
find_by_xyz
find_by_sql

:first :all :conditions :include :order :limit :select :joins :offset :readonly :lock
etc...

Getting into details, previously we created few rows about user into users table. Now we use this find to read/retrieve the data. Little about "find", it is counterpart for "select * from users" in SQL. The syntax is very plain and simple to pick up.
Say, now I want to read/retrieve the data of all users.

User.find(:all)
so the find method connects to users table (through User class of model) and through parameter "all" it fetches info of all the users a simple array. If we use parameter :first, then only first record would be fetched.
User.find(:first)
say now I want to introduce some constraints. :conditions is the parameter to be used.
Like, I want user with a specific name
User.find(:first,
:conditions => "name='sumanth'" )

but in case the name to be matched comes dynamically through params, then there would be slight change in the above syntax. Like this,
User.find(:first,
:conditions => "name=?,params[:name] ")

or

User.find(:first,
:conditions => "name= '#{
params[:name] }'")


if you want more than one parameter to be checked/matched in the conditions then we can separate each with 'and'.

User.find(:first,
:conditions => ["name=? and email=?",params[:name] ,params[:email]])
thus we can play around with more options/parameter that "find" accommodates. Don't forget to separate each options with "," as I had used it after :first and before :conditions options.

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.
Create
Read
Update
Delete
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 (u.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.

Thursday, March 13

ActiveRecord association has_many :through

We had seen how a has_and_belongs_to_many works with a join table. But apart from carrying the foreign keys the join table has nothing much to do over there. So to have more features added and retaining the goal of having many-to-many relationships we will discuss now another rails offering "has_many, :through".

The above snippet shows a simple example from Josh Susser's blog.
The scenario shows that there are two tables "books" and "contributors" and the a join table "contributions". This is entirely different from habtm, where we had the join table with combination of tables.
And syntactically, we say to each of tables (books, contributors) that they are related to each other through "contributions".
So the join table would have a simple belongs_to and the individual tables will be related with has_many:'table_name' and keyword :through=>'name_of_join_table'

That is with the ActiveRecord relationships. Just to recap
has_and_belongs_to_many
has_many, has_one, belongs_to

We will be slowly moving into other part of rails packages, ActionPack soon.

Wednesday, February 13

Relationships between tables - How ActiveRecord handles?

Keywords:
  • has_one,
  • belongs_to,
  • has_many,
  • has_and_belongs_to_many
  • polyphormic
  • one-to-one
  • one-to-many
  • many-to-many
It's known that any web application will contain bunch of tables and they are dependent on each other. With normalization as the key, we avoid redundancy and have more relationships with tables using keys. In database terms, the following are the relations allowed/known between tables -> one-to-one, one-to-many, many-to-many. Let us digg more, how ActiveRecord handles these.
ActiveRecord supports the above mentioned relations and in fact, comes with set of key words which are easy to use, understand and pretty clean.
Let me take few snapshots from David's book:
Note:
  1. invoices is the table name
  2. orders is the table name
In the above snaphot, the motive is to declare the relationship between the orders and invoices tables. It's clear that orders will have invoices, i.e., invoices belong to orders. And watch out we will be using same words. Now to have the relationship declared, we will go to their models (Remember: the application access the tables through model so it makes sense to declare relationships also in models).

Now I am into order model, orders having invoices. so the key word that we use here is has_one and then followed by the model name (Note: It is not table name, this is not plural).
has_one :invoice

Next will go to invoice model, since invoices belongs to orders we use the key word belongs_to and then followed by the model name.
belongs_to :order

Well there is not xml written for models, no xml written for relationships. But simple convention and defined keywords done the job for us.
And as you might have guessed the has_many comes into use when the orders table is having relationship with one more table (say, line_items). The below snapshot will help you to understand the syntax and it's usage.

Will look into other keywords and other relationship in the following posts...

Monday, February 4

ActiveRecord - Pluralization convention

In the previous post, we had seen how simply we had connected our database to the application. Now let us look in to another convention wherein, you need not have a xml file to connect each table in the database to the classes (Note: class is the blue print from where we create objects) in our application.
The convention here followed is English way of singular and plural forms. The database is nothing but collection of records, data in specific structure. And a 'class' as per Object Oriented Paradigm, it is a constructor and you can have multiple objects of similar type from it!
So it absolutely makes sense to name our tables in plural form (collection of data) and a class in the singular form.
Rails just does that! we name the tables of database as plurals and the respective classes as singular form of the same.

The above snapshot is taken from David's book on rails. As it shown here, we maintain the singular form on to the class names and plural on the table names.
Rails literally understands the singular and plural form of the words you use.

Order orders
Person people

You take a note of the way we write the names:
  • the table names in plural form all lower case letters.
  • the class name in singular form with camel case/capitalized word
Of course, I am sure you have few questions running into your mind:
  1. What if the word does not have proper plural form?
  2. What if I do not want to follow this?
The answers are:
  1. As you can see in the above snapshot, the 'Person' as the class name and 'people' as the table name. And if you do not have proper/matching form for it, or you did not maintain the convention mentioned - you can use a keyword called set_table_name, in the model class where ever you are defining the construct.
  2. You can disable this feature globally with a variable under 'config/environment.rb' of the application. ActiveRecord::Base.pluralize_table_names = false
Well, this is just a convention that help avoid writing/maintaining lot of xml files and connection problems. Let me also tell you that it is not mandatory to have this maintained strictly.
I guessed only the above questions, if you have more questions touch base with me and get them clarified.

Tuesday, January 29

ActiveRecord Databases - II

In the previous post, I just shown how do you tell your application the whereabouts of the database(s) that's in use. Now we are left out with task to connect each tables. Let me remind you again, this would need configuring/customizing lots of xml files in java based applications.
You may ask:
Come on, How do you achieve it without the xml files?
Well the magic here is usage of, pluralisation of tables and respective singular form for it's class names.

Can you show me how to do it?
hmmm... of course.
In last post we modified database.yml of our "dummy" project.

adapter: mysql
database: dummy
username: root
password:
host: localhost

Just recollect, this shows our "dummy" project is referencing to database by name "dummy". I am creating the database related tables, objects (rows), columns (properties) using a tool called phpMyAdmin.

Assuming that this "dummy" database contains a table with user information. So our convention would suggest to have table name in plural form. Let's call it as "users". Now we need to have a class created with singular form of the "users" -> "user", and respective logic relating to the table would go into/under this class.
class User <>

end

Let us diagnose a bit the above code. Recollect the convention we talked above, and the ORM concept. This means that the applications having class called "User" which would connect/contact to database table by name "users" (the database info is set up in database.yml).

We will slowly getting into the code and we keep developing or adding more functionalities to our "dummy" project.

Do I need to use only mysql as the database?
Not exactly and need not be. The following table would give the info related to configure each database and the respective parameters:


Well more action and fun is on the way :)

Monday, January 28

ActiveRecord Databases - I

One of the main features that rails do support on is Convention over Configuration. Well repeat again and again Convention over Configuration. Let it get into the minds!
Well it is spread across the rails framework with which will be developing an application. I will be reminding whenever it's put in use.
In previous post, I did stress on how simple it would be in configuring the databases and tables with your application. In Java based applications, this would be done using lot of xml files, which is of course, time taking, lot of repetitive work and error prone... (at least that's what my friend's used to say!).

Well in rails this is not the case a simple convention that you follow would ensure of configuring the tables of databases.
"You name the tables in database as plurals and create classes with singular form of the table names."
Configuring the Databases:
The choice of which database you use the configuration and respective adapter would depend on. When we created an application, there is a set of predefined folders created over a simple command! (I will touch upon this later). "config" is one such folder and under this we will now concentrate/repair on "database.yml".
Rails would automatically create 3 different environments:
  1. Development
  2. Test
  3. Production
Based on the environment we work on we need to edit the data accordingly. (More on environments will be covered sooner!)
This file contains the information relate to the adapter, database, user credentials, host, port...

This does make sense in a way, the plural form for tables will fit as it contains huge data and the respective class which we would be placed under app/models, with the extension ".rb" is named in singular form.


development:
adapter: mysql
database: dummy
username: root
password:
host: localhost

What it means?
Our application is connected to MySQL database by name dummy, user being and root and with an empty password. The host environment is "localhost".

To Be Continued...

Web Applications

Database is one of the key things for the web applications. The flow of web application can be simply put into the following broad steps:

  • User makes request from Browser/Client
  • The "http" request carries this to Server (web/app server)
  • The web server parts the request with the help of CGI/FCGI...
  • CGI/FCGI gives the control to application
  • Application takes the rest of game, which include
    • Identifying the actions/method
    • Actions/Methods would do the logic
    • Contacts the database
    • Fetches the data and pushes to front (with appropriate html's...)
  • The server would redirect the same to client side.
  • The user gets the content he asked for.
That would give good picture on how the web application work.
The above points give us information on what are the components that are required and each of them will be covered in the posts coming upon!

Tuesday, January 15

Ruby on Rails - Installing Rails

Recently my laptop crashed as the virus invaded to each and every folder possible. I could not open any of local folders, files and also not able to access the internet. I was so fed up, without second thought I just reformatted my system. Of course, later I realized the value of backup, when I was going through the installations.
Adding to this when I tried to install rails through "gem install rails --include-dependencies". It was annoying message, which said the request to remote server timed out!

Well I was just discussing with my juniors what exactly rails consists/made of?
Rails is nothing but Web-application framework with template engine, control-flow layer, and ORM.
I also explained that they are nothing but few ruby files called/named as gems.
activeresource, rails, activesupport, activerecord, actionpack,
I recollected that, and instead of depending on net connection speed, went to ruby forge and picked up all the above gems (latest version 2.0.2) and stored on to local folders. Then installed one by one in the order... (click the links to download)
  1. activeresource 2.0.2
  2. rails 2.0.2
  3. activesupport 2.0.2
  4. activerecord 2.0.2
  5. actionpack 2.0.2
  6. actionmailer 2.0.2
Download the archive.
Note: The order is maintained based on the dependencies the other
So this is what downloaded/installed when you run the command "gem install rails --include-dependencies".


Though each of the above listed gems could become a topic by itself, let me brief what's the role each of them got to play:
  • activeresource - Think Active Record for web resources.
  • rails - Web-application framework with template engine, control-flow layer, and ORM.
  • activesupport - Support and utility classes used by the Rails framework.
  • activerecord - Implements the ActiveRecord pattern for ORM.
  • actionpack - Web-flow and rendering framework putting the VC (Views & Controllers) in MVC
  • actionmailer - Service layer for easy email delivery and testing.
The embedded image shows the list of gems that will be installed, when you install ruby, rails.

Thanks to my friend Manoj for the screenshot.
Cross check:
  1. ruby -v => To check the version of ruby installed
  2. gem -v => To check the version of gems installed
  3. rails -v => To check the version of rails installed
  4. gemlist => To find the list of all gems installed