Search This Blog

Monday, September 3, 2012

ROR more concepts

Control over caching:
ActiveRecord comes in handy for doing lot of operations on associated tables and models.
For example, consider the following scenario

class Person <ActiveRecord::Base

    has_many: accounts
end

class Account <ActiveRecord::Base

   belongs_to: person
end

in the above case , the following association is made,

a person has many accounts and each account belongs to one person.

This association creates many methods automatically with the help of meta programming!
one such method is 'accounts',a instance method for Person class.
we can do,
@person1.accounts
this will fetch all accounts of person1.
next we do,
@person1.accounts.size
this will tell number of accounts of person1. Normally people would expect that the above statement will run some query again to find the size. But its not the case. During first statement itself @person.accounts is cached. Next time when we do, @person.accounts.size the cached copy is only used, thus saving lot of time !
What if we specifically require to fire a new query for finding size (since some other application could have changed the database in meantime). There is a way to achieve it.
@person.accounts(true).size
will fetch the current size after executing a new query instead of using cached version of orders.

My experience today:
Probably many might not have heard about collaborative story writing . There are few websites for the purpose though. It means user's registered in the website can start writing a story and also contribute to  stories written by other users. I took up this application for learning Rails. Today is my first day. I implemented sign up,sign in and other authentication stuffs using devise gem.
Its a very neat and efficient gem for doing all sort of functionality like "forgot password" , "remember me" etc..
I designed the basic schema of my application and started coding.
I implemented "edit profile" functionality for users. It would seem very less for a day. But as i mentioned in my previous post learning curve of rails is very steep. I will be able to speed up once i get hold of Rails :)
See you in next post with more interesting stuffs! stay in touch.

No comments:

Post a Comment