<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Vrkhamke</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Vrkhamke"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Vrkhamke"/>
	<updated>2026-08-23T13:32:34Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68152</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68152"/>
		<updated>2012-10-25T03:21:03Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Listening */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming is a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
The main goals are:&lt;br /&gt;
# attempt to reduce the cost of changes in requirements by having multiple short development cycles&lt;br /&gt;
# changes are a natural and a desirable aspect of software-development projects, and should be planned for in advance.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: designing, coding, testing, listening as described below:&lt;br /&gt;
&lt;br /&gt;
====Coding====&lt;br /&gt;
&lt;br /&gt;
The guiding principle of XP is that without code, there is no working product. Hence, importance is given to code rather than documentation for various aspects.&lt;br /&gt;
&lt;br /&gt;
Coding can also help to communicate thoughts about problems. A programmer dealing with a complex programming problem, might prototype it in a simplified manner and use it to demonstrate what he or she means. Code is always clear and concise and makes the problem unambiguous.&lt;br /&gt;
&lt;br /&gt;
====Testing====&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that a lot of testing can eliminate many flaws in the product.&lt;br /&gt;
&lt;br /&gt;
Unit tests are performed to determine whether a given unit of the product works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code. Only if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the components delivered the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
====Listening====&lt;br /&gt;
&lt;br /&gt;
The Programmers must listen to what the customer requirements are clearly, and what &amp;quot;business logic&amp;quot; is needed and give feedback about the technical aspects of how the problem might be solved, or cannot be solved. Effective communication between the customer and the development team is essential to get the product working as intended. Hence, listening is a very important aspect of XP.&lt;br /&gt;
&lt;br /&gt;
====Designing====&lt;br /&gt;
&lt;br /&gt;
Creating a design structure organizes the components of the system. Good design will avoid lots of dependencies within a system and will focus on low coupling and high cohesion. Without a proper design the system becomes too complex and the dependencies within the system cease to be clear.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68151</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68151"/>
		<updated>2012-10-25T03:18:54Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Listening */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming is a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
The main goals are:&lt;br /&gt;
# attempt to reduce the cost of changes in requirements by having multiple short development cycles&lt;br /&gt;
# changes are a natural and a desirable aspect of software-development projects, and should be planned for in advance.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: designing, coding, testing, listening as described below:&lt;br /&gt;
&lt;br /&gt;
====Coding====&lt;br /&gt;
&lt;br /&gt;
The guiding principle of XP is that without code, there is no working product. Hence, importance is given to code rather than documentation for various aspects.&lt;br /&gt;
&lt;br /&gt;
Coding can also help to communicate thoughts about problems. A programmer dealing with a complex programming problem, might prototype it in a simplified manner and use it to demonstrate what he or she means. Code is always clear and concise and makes the problem unambiguous.&lt;br /&gt;
&lt;br /&gt;
====Testing====&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that a lot of testing can eliminate many flaws in the product.&lt;br /&gt;
&lt;br /&gt;
Unit tests are performed to determine whether a given unit of the product works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code. Only if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the components delivered the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
====Listening====&lt;br /&gt;
&lt;br /&gt;
The Programmers must listen to what the customer requirements are clearly, and what &amp;quot;business logic&amp;quot; is needed and give feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the Planning Game.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====Designing====&lt;br /&gt;
&lt;br /&gt;
Creating a design structure organizes the components of the system. Good design will avoid lots of dependencies within a system and will focus on low coupling and high cohesion. Without a proper design the system becomes too complex and the dependencies within the system cease to be clear.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68150</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68150"/>
		<updated>2012-10-25T03:14:36Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Testing */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming is a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
The main goals are:&lt;br /&gt;
# attempt to reduce the cost of changes in requirements by having multiple short development cycles&lt;br /&gt;
# changes are a natural and a desirable aspect of software-development projects, and should be planned for in advance.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: designing, coding, testing, listening as described below:&lt;br /&gt;
&lt;br /&gt;
====Coding====&lt;br /&gt;
&lt;br /&gt;
The guiding principle of XP is that without code, there is no working product. Hence, importance is given to code rather than documentation for various aspects.&lt;br /&gt;
&lt;br /&gt;
Coding can also help to communicate thoughts about problems. A programmer dealing with a complex programming problem, might prototype it in a simplified manner and use it to demonstrate what he or she means. Code is always clear and concise and makes the problem unambiguous.&lt;br /&gt;
&lt;br /&gt;
====Testing====&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that a lot of testing can eliminate many flaws in the product.&lt;br /&gt;
&lt;br /&gt;
Unit tests are performed to determine whether a given unit of the product works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code. Only if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the components delivered the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
===Listening===&lt;br /&gt;
&lt;br /&gt;
Programmers must listen to what the customers need the system to do, what &amp;quot;business logic&amp;quot; is needed. They must understand these needs well enough to give the customer feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the Planning Game.&lt;br /&gt;
Designing&lt;br /&gt;
&lt;br /&gt;
From the point of view of simplicity, of course one could say that system development doesn't need more than coding, testing and listening. If those activities are performed well, the result should always be a system that works. In practice, this will not work. One can come a long way without designing but at a given time one will get stuck. The system becomes too complex and the dependencies within the system cease to be clear. One can avoid this by creating a design structure that organizes the logic in the system. Good design will avoid lots of dependencies within a system; this means that changing one part of the system will not affect other parts of the system.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68149</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68149"/>
		<updated>2012-10-25T03:12:19Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Coding */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming is a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
The main goals are:&lt;br /&gt;
# attempt to reduce the cost of changes in requirements by having multiple short development cycles&lt;br /&gt;
# changes are a natural and a desirable aspect of software-development projects, and should be planned for in advance.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: designing, coding, testing, listening as described below:&lt;br /&gt;
&lt;br /&gt;
====Coding====&lt;br /&gt;
&lt;br /&gt;
The guiding principle of XP is that without code, there is no working product. Hence, importance is given to code rather than documentation for various aspects.&lt;br /&gt;
&lt;br /&gt;
Coding can also help to communicate thoughts about problems. A programmer dealing with a complex programming problem, might prototype it in a simplified manner and use it to demonstrate what he or she means. Code is always clear and concise and makes the problem unambiguous.&lt;br /&gt;
&lt;br /&gt;
===Testing===&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that if a little testing can eliminate a few flaws, a lot of testing can eliminate many more flaws.&lt;br /&gt;
&lt;br /&gt;
Unit tests determine whether a given feature works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code; if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the requirements as understood by the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
===Listening===&lt;br /&gt;
&lt;br /&gt;
Programmers must listen to what the customers need the system to do, what &amp;quot;business logic&amp;quot; is needed. They must understand these needs well enough to give the customer feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the Planning Game.&lt;br /&gt;
Designing&lt;br /&gt;
&lt;br /&gt;
From the point of view of simplicity, of course one could say that system development doesn't need more than coding, testing and listening. If those activities are performed well, the result should always be a system that works. In practice, this will not work. One can come a long way without designing but at a given time one will get stuck. The system becomes too complex and the dependencies within the system cease to be clear. One can avoid this by creating a design structure that organizes the logic in the system. Good design will avoid lots of dependencies within a system; this means that changing one part of the system will not affect other parts of the system.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68148</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68148"/>
		<updated>2012-10-25T03:08:37Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Activities */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming is a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
The main goals are:&lt;br /&gt;
# attempt to reduce the cost of changes in requirements by having multiple short development cycles&lt;br /&gt;
# changes are a natural and a desirable aspect of software-development projects, and should be planned for in advance.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: designing, coding, testing, listening as described below:&lt;br /&gt;
&lt;br /&gt;
===Coding===&lt;br /&gt;
&lt;br /&gt;
The advocates of XP argue that the only truly important product of the system development process is code – software instructions that a computer can interpret. Without code, there is no working product.&lt;br /&gt;
&lt;br /&gt;
Coding can also be used to figure out the most suitable solution. Coding can also help to communicate thoughts about programming problems. A programmer dealing with a complex programming problem, or finding it hard to explain the solution to fellow programmers, might code it in a simplified manner and use the code to demonstrate what he or she means. Code, say the proponents of this position, is always clear and concise and cannot be interpreted in more than one way. Other programmers can give feedback on this code by also coding their thoughts.&lt;br /&gt;
&lt;br /&gt;
===Testing===&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that if a little testing can eliminate a few flaws, a lot of testing can eliminate many more flaws.&lt;br /&gt;
&lt;br /&gt;
Unit tests determine whether a given feature works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code; if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the requirements as understood by the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
===Listening===&lt;br /&gt;
&lt;br /&gt;
Programmers must listen to what the customers need the system to do, what &amp;quot;business logic&amp;quot; is needed. They must understand these needs well enough to give the customer feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the Planning Game.&lt;br /&gt;
Designing&lt;br /&gt;
&lt;br /&gt;
From the point of view of simplicity, of course one could say that system development doesn't need more than coding, testing and listening. If those activities are performed well, the result should always be a system that works. In practice, this will not work. One can come a long way without designing but at a given time one will get stuck. The system becomes too complex and the dependencies within the system cease to be clear. One can avoid this by creating a design structure that organizes the logic in the system. Good design will avoid lots of dependencies within a system; this means that changing one part of the system will not affect other parts of the system.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68147</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68147"/>
		<updated>2012-10-25T03:07:38Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Goals */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming is a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
The main goals are:&lt;br /&gt;
# attempt to reduce the cost of changes in requirements by having multiple short development cycles&lt;br /&gt;
# changes are a natural and a desirable aspect of software-development projects, and should be planned for in advance.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: coding, testing, listening, and designing. Each of those activities is described below.&lt;br /&gt;
&lt;br /&gt;
===Coding===&lt;br /&gt;
&lt;br /&gt;
The advocates of XP argue that the only truly important product of the system development process is code – software instructions that a computer can interpret. Without code, there is no working product.&lt;br /&gt;
&lt;br /&gt;
Coding can also be used to figure out the most suitable solution. Coding can also help to communicate thoughts about programming problems. A programmer dealing with a complex programming problem, or finding it hard to explain the solution to fellow programmers, might code it in a simplified manner and use the code to demonstrate what he or she means. Code, say the proponents of this position, is always clear and concise and cannot be interpreted in more than one way. Other programmers can give feedback on this code by also coding their thoughts.&lt;br /&gt;
&lt;br /&gt;
===Testing===&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that if a little testing can eliminate a few flaws, a lot of testing can eliminate many more flaws.&lt;br /&gt;
&lt;br /&gt;
Unit tests determine whether a given feature works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code; if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the requirements as understood by the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
===Listening===&lt;br /&gt;
&lt;br /&gt;
Programmers must listen to what the customers need the system to do, what &amp;quot;business logic&amp;quot; is needed. They must understand these needs well enough to give the customer feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the Planning Game.&lt;br /&gt;
Designing&lt;br /&gt;
&lt;br /&gt;
From the point of view of simplicity, of course one could say that system development doesn't need more than coding, testing and listening. If those activities are performed well, the result should always be a system that works. In practice, this will not work. One can come a long way without designing but at a given time one will get stuck. The system becomes too complex and the dependencies within the system cease to be clear. One can avoid this by creating a design structure that organizes the logic in the system. Good design will avoid lots of dependencies within a system; this means that changing one part of the system will not affect other parts of the system.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68146</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w8 vp</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w8_vp&amp;diff=68146"/>
		<updated>2012-10-25T03:02:58Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Concepts of XP */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Extreme programming (XP)=&lt;br /&gt;
This chapter focuses on explaining below points.&lt;br /&gt;
Describe what extreme programming is. &lt;br /&gt;
Concepts of XP. &lt;br /&gt;
Four values in XP. &lt;br /&gt;
Aspects in key practices such as pair programming, collective code ownership, stories, automated testing, small releases and continuous integration. &lt;br /&gt;
Advantages and Disadvantages with XP.&lt;br /&gt;
Comparison with waterfall model&lt;br /&gt;
[[File:Extreme.jpg| right]]&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
== What is extreme programming ==&lt;br /&gt;
Extreme Programming (XP) is a software development methodology created by Kent Beck during his work on the Chrysler Comprehensive Compensation System (C3) payroll project. Extreme Programming is intended to improve software quality and responsiveness to changing customer requirements. It is a one of the several types of agile software development processes. Extreme Programming is successful because it stresses customer satisfaction. Instead of delivering everything you could possibly want on some date far in the future this process delivers the software you need as you need it. Extreme Programming empowers developers to confidently respond to changing customer requirements, even late in the life cycle.&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Concepts of XP ==&lt;br /&gt;
&lt;br /&gt;
===Goals===&lt;br /&gt;
&lt;br /&gt;
Extreme Programming Explained describes Extreme Programming as a software-development discipline that organizes people to produce higher quality software more productively.&lt;br /&gt;
&lt;br /&gt;
XP attempts to reduce the cost of changes in requirements by having multiple short development cycles, rather than a long one. In this doctrine, changes are a natural, inescapable and desirable aspect of software-development projects, and should be planned for, instead of attempting to define a stable set of requirements.&lt;br /&gt;
&lt;br /&gt;
Extreme programming also introduces a number of basic values, principles and practices on top of the agile programming framework.&lt;br /&gt;
&lt;br /&gt;
===Activities===&lt;br /&gt;
&lt;br /&gt;
XP describes four basic activities that are performed within the software development process: coding, testing, listening, and designing. Each of those activities is described below.&lt;br /&gt;
&lt;br /&gt;
===Coding===&lt;br /&gt;
&lt;br /&gt;
The advocates of XP argue that the only truly important product of the system development process is code – software instructions that a computer can interpret. Without code, there is no working product.&lt;br /&gt;
&lt;br /&gt;
Coding can also be used to figure out the most suitable solution. Coding can also help to communicate thoughts about programming problems. A programmer dealing with a complex programming problem, or finding it hard to explain the solution to fellow programmers, might code it in a simplified manner and use the code to demonstrate what he or she means. Code, say the proponents of this position, is always clear and concise and cannot be interpreted in more than one way. Other programmers can give feedback on this code by also coding their thoughts.&lt;br /&gt;
&lt;br /&gt;
===Testing===&lt;br /&gt;
&lt;br /&gt;
Extreme programming's approach is that if a little testing can eliminate a few flaws, a lot of testing can eliminate many more flaws.&lt;br /&gt;
&lt;br /&gt;
Unit tests determine whether a given feature works as intended. A programmer writes as many automated tests as they can think of that might &amp;quot;break&amp;quot; the code; if all tests run successfully, then the coding is complete. Every piece of code that is written is tested before moving on to the next feature.&lt;br /&gt;
Acceptance tests verify that the requirements as understood by the programmers satisfy the customer's actual requirements.&lt;br /&gt;
&lt;br /&gt;
===Listening===&lt;br /&gt;
&lt;br /&gt;
Programmers must listen to what the customers need the system to do, what &amp;quot;business logic&amp;quot; is needed. They must understand these needs well enough to give the customer feedback about the technical aspects of how the problem might be solved, or cannot be solved. Communication between the customer and programmer is further addressed in the Planning Game.&lt;br /&gt;
Designing&lt;br /&gt;
&lt;br /&gt;
From the point of view of simplicity, of course one could say that system development doesn't need more than coding, testing and listening. If those activities are performed well, the result should always be a system that works. In practice, this will not work. One can come a long way without designing but at a given time one will get stuck. The system becomes too complex and the dependencies within the system cease to be clear. One can avoid this by creating a design structure that organizes the logic in the system. Good design will avoid lots of dependencies within a system; this means that changing one part of the system will not affect other parts of the system.&lt;br /&gt;
&lt;br /&gt;
== Four values in XP ==&lt;br /&gt;
*Simplicity:&lt;br /&gt;
Keeping code simple makes changing code easier as the requirements inevitably change. Simple solutions to today's problems minimizes the cost of change over time. For example it is ten times harder to fix a mistake of requirements when you are in the design phase, and 100 times harder to make changes late in a project during the coding phase. simple designs minimizes the risk of spending a long time designing sophisticated frameworks that the customer may not use/want.&lt;br /&gt;
[[File:simple.jpg| center]]&lt;br /&gt;
One important point to note is that XP approach recognizes that the cost of change generally increases like one would expect, but this increase is not always increasing. If the code is refactored and kept simple, we can avoid ever-increasing complexity.&lt;br /&gt;
&lt;br /&gt;
*Communication:&lt;br /&gt;
Different Types of Communication:&lt;br /&gt;
With respect to programmers, code communicates best when it is simple else once should strive to simplify it.&lt;br /&gt;
Another form of communication is Unit Tests, Unit tests exercise the classes and methods in your application,Unit tests communicate the design of a class effectively.&lt;br /&gt;
Programmers communicate to with one another because they program in pairs(Pair Programming).There is no set observer in a pair.&lt;br /&gt;
XP requires an on-site customer to convey the requirements to the team. The customer decides which features are most important, and is always available to answer questions.&lt;br /&gt;
&lt;br /&gt;
*Feedback:&lt;br /&gt;
On-site customer the means to get immediate feedback about the project status. There are short release cycles, where the customer is able to evaluate each new feature as it is developed, minimizing the necessity to rework and helping the programmers focus on what is most important to the customer. The customer always defines which features are the most important, so the most valuable features are delivered early in the project. Customers can cancel the project at any time and have a working system with the features as per the last release.&lt;br /&gt;
&lt;br /&gt;
*Courage:&lt;br /&gt;
For managers, the concept of pair programming can be hard to accept—it seems like productivity will drop by 50%, because only half of the programmers are writing code at any given time. It takes courage to trust that pair programming improves quality without slowing down progress. It takes courage to implement the feature the customer is asking for today using a simple approach, because you probably want to build in flexibility to account for tomorrow's features, as well.Everyone gives and feels the respect they deserve as a valued team member. Everyone contributes value even if it's simply enthusiasm. Developers respect the expertise of the customers and vice versa. Management respects our right to accept responsibility and receive authority over our own work.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Aspects in key practices ==&lt;br /&gt;
There are 19 key practices:&lt;br /&gt;
*Joint&lt;br /&gt;
*Common Vocabulary&lt;br /&gt;
*Iterations&lt;br /&gt;
*Open Workspace&lt;br /&gt;
*Retrospectives&lt;br /&gt;
*Development&lt;br /&gt;
*Test-First Development&lt;br /&gt;
*Pair Programming&lt;br /&gt;
*Refactoring&lt;br /&gt;
*Collective Ownership&lt;br /&gt;
*Continuous Integration&lt;br /&gt;
*Just-In-Time Design&lt;br /&gt;
*Customer&lt;br /&gt;
*Storytelling&lt;br /&gt;
*Release Planning&lt;br /&gt;
*Acceptance Tests&lt;br /&gt;
*Frequent Releases&lt;br /&gt;
*Management&lt;br /&gt;
*Accepted Responsibility&lt;br /&gt;
*Air Cover&lt;br /&gt;
*Quarterly Review&lt;br /&gt;
*Mirror&lt;br /&gt;
*Sustainable Pace&lt;br /&gt;
&lt;br /&gt;
Lets understand some of the practices in more detail.&lt;br /&gt;
&lt;br /&gt;
Pair-Programming:&amp;lt;br&amp;gt;&lt;br /&gt;
XP teams work in pairs where they share a single computer, keyboard, and mouse. &lt;br /&gt;
&lt;br /&gt;
Flow:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
*Programmer picks a User Story.&lt;br /&gt;
*Programmer1 asks for help from another Programmer2.&lt;br /&gt;
*Programmer1 and Programmer2 work to implement the functionality.&lt;br /&gt;
*After the immediate task is completed, programmer1 picks another partner to complete the remaining task or offers help to someone else.&lt;br /&gt;
&lt;br /&gt;
Advantage:&amp;lt;br&amp;gt;&lt;br /&gt;
*Partners rotate frequently and hence facilitate communication.&lt;br /&gt;
*Paring with experienced programmers beginners gain valuable coding experience.&lt;br /&gt;
*While one person writes programs other gets time to think about the problem at higher level of abstraction.&lt;br /&gt;
 &lt;br /&gt;
Collective Ownership:&lt;br /&gt;
*Every team member can work on any part of code in the application. There is constant shuffling and change of roles.&lt;br /&gt;
*Collective code ownership works because any team member can ask for help when he/she works on unfamiliar classes.&lt;br /&gt;
*It’s easier to catch errors when you have a set of unit cases to rely on. If a new change introduced by a partner breaks the code, it can be easily tracked before the code is integrated.&lt;br /&gt;
*Shared ownership model avoids the problem situations where the entire team depends on the one person who understands a part of code.&lt;br /&gt;
*It encourages high design quality because every functionality is subject to continuous refactor and modification.&lt;br /&gt;
&lt;br /&gt;
User – Stories:&amp;lt;br&amp;gt;&lt;br /&gt;
*Used to estimate for the release planning meeting.&lt;br /&gt;
*Easy to comprehend as compared to large requirement documents.&lt;br /&gt;
*Very intuitive since they reflect what customers expect hence drive the creation of acceptance test.&lt;br /&gt;
*User stories provide enough detail to make a low risk estimate of the time the story will take to implement.&lt;br /&gt;
*Each story will be 1, 2 or 3 week estimate in &amp;quot;ideal development time&amp;quot; which is the time it would take to implement the story in code if there were no distractions and the programmers know what to do. If its more than 3 weeks then the stories need to be broken down into simpler stories.&lt;br /&gt;
*Avoid details of technology, data base layout, and algorithms being used.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Advantages of XP ==&lt;br /&gt;
*Built-In Quality&lt;br /&gt;
*Overall Simplicity&lt;br /&gt;
*Programmer Power&lt;br /&gt;
*Customer Power&lt;br /&gt;
*Synergy Between Practices&lt;br /&gt;
*Coding Standards – Reduces the amount of time developers spend reformatting other peoples’ code. Reduces the need  for internal commenting. Call for clear, unambiguous code&lt;br /&gt;
*On-Site Customer - Can give quick and knowledgeable answers to real development questions. Makes sure that what is developed is what is needed. Functionality is prioritized correctly&lt;br /&gt;
*40-Hour Week – Most developers lose effectiveness past 40-Hours. Value is placed on the developer’s well-being. Management is forced to find real solutions&lt;br /&gt;
*Continuous Integration - Reduces to lengthy process. Enables the Small Releases practice&lt;br /&gt;
*Collective Ownership - Helps mitigate the loss of a team member leaving. Promotes developers to take responsibility for the system as whole rather than parts of the system&lt;br /&gt;
*Pair Programming – Two heads are better than one. Focus Two people are more likely to answer the following questions: Is this whole approach going to work? What are some test cases that may not work yet? Is there a way to simplify this?&lt;br /&gt;
*Refactoring – Prompts developers to proactively improve the product as a whole. Increases developer knowledge of the system&lt;br /&gt;
*Testing – Unit testing promote testing completeness. Test-first gives developers a goal. Automation gives a suite of regression test&lt;br /&gt;
*Simple Design – Time is not wasted adding superfluous functionality. Easier to understand what is going on. Refactoring and collective ownership is made possible. Helps keeps programmers on track&lt;br /&gt;
*Metaphor – Encourages a common set of terms for the system. Reduction of buzz words and jargon. A quick and easy way to explain the system&lt;br /&gt;
*Small Releases – Frequent feedback. Tracking. Reduce chance of overall project slippage&lt;br /&gt;
*The Planning Game – Reduction in time wasted on useless features. Greater customer appreciation of the cost of a feature. Less guesswork in planning&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Disadvantages of XP==&lt;br /&gt;
&lt;br /&gt;
*Informal, little, or no documentation&lt;br /&gt;
*Scalability&lt;br /&gt;
*Contract Issues&lt;br /&gt;
*Misconception on the cost of change&lt;br /&gt;
*Tailoring&lt;br /&gt;
*Coding Standards – Degrading the quality of inline documentation&lt;br /&gt;
*On-Site Customer – Difficult to get an On-Site Customer. The On-Site customer that is given may not be fully knowledgeable about what the company may not have authority to make many decisions. Loss of work to the customer’s company.&lt;br /&gt;
*40-Hour Week - The underlying principle is flawed. 40-Hours is a magic number. Some may like to work more than 40-Hours&lt;br /&gt;
*Continuous Integration – The one day limit is not always practical. Reduces the importance of a well-thought-out architecture&lt;br /&gt;
*Collective Ownership - Loss of accountability. Limitation to how much of a large system that an individual can practically “own”&lt;br /&gt;
*Pair Programming – Many tasks really don’t require two programmers. A hard sell to the customers. Not for everyone&lt;br /&gt;
*Refactoring – Not everyone is capable of refactoring. Refactoring may not always be appropriate. Would upfront design eliminate refactoring?&lt;br /&gt;
*Testing – Automated unit testing isn’t for everything. Reliance on unit testing isn’t a good idea. A test result is only as good as the test itself&lt;br /&gt;
*Simple Design – What is “simple?”. Simple isn’t always best&lt;br /&gt;
*Metaphor – Often the metaphor is the system. Another opportunity for miscommunication. The system is often not well understood as a metaphor&lt;br /&gt;
*Small Releases – Not easy for all projects. Not needed for all projects. Versioning issues&lt;br /&gt;
*The Planning Game – Customer availability. Is planning this often necessary?&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Comparison with waterfall model ==&lt;br /&gt;
Waterfall approach emphasizes on clear definition from the beginning of project. Its strengths are ability to analyse potential changes easily, large and distributed teams are well-coordinated, predictable budgets, and only needs small involvement from subject matter experts. But there are some clear disadvantages also. For example lack of flexibility, difficulty in predicting actual needs for the software, the loss of intangible knowledge between phases, discouragement of team cohesion, and the tendency to not discover design flaws until the testing phase. In reality it is very difficult for projects to follow the sequential flow of the model. It is difficult to identify all requirements and goals at the beginning of projects as requirements tend to change all the way. A working version can only be obtained late in the process.&lt;br /&gt;
 &lt;br /&gt;
Below is a picture of how agile methodologies differ from traditional waterfall model.&lt;br /&gt;
[[File:Agile-1.jpg| left]]&lt;br /&gt;
[[File:waterfall-1.png| center]]&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== Research Conclusion ==&lt;br /&gt;
Research was carried out in Carnegie Mellon University where data collected was from five years of 50 teams, developing the same project each year and the affects of transitioning from Waterfall to Extreme Programming was analyzed. The characteristics between these two methods were evaluated and compared. According to the paper, waterfall teams spent more time creating high ceremony documents where as Extreme Programming teams spent more time writing code and documenting their design in their code.  Surprisingly, the amount of code and features completed were roughly the same for both methods suggesting that on a three month project with three to four developers it didn't matter the method used. Please refer the references for the research paper.&lt;br /&gt;
&lt;br /&gt;
[[#top|Back to top]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
&amp;lt;references&amp;gt;&lt;br /&gt;
&amp;lt;/references&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[ http://www.cutter.com/content-and-analysis/resource-centers/agile-project-management/sample-our-research/ead0002/ead0002.pdf  Cutter Agile Project Management]&lt;br /&gt;
#[ http://en.wikipedia.org/wiki/Extreme_programming Extreme Programming Wikipedia ]&lt;br /&gt;
#[ http://www.cs.usfca.edu/~parrt/course/601/lectures/xp.html USF Lectures on Extreme Programming]&lt;br /&gt;
#[ http://www.computerworld.com/s/article/66192/Extreme_Programming?taxonomyId=063 Computerworld Articles Extreme Programming]&lt;br /&gt;
#[ http://www.extremeprogramming.org ExtremeProgramming.org]&lt;br /&gt;
#[ http://www.jera.com/techinfo/xpfaq.html Jera Extreme Programming]&lt;br /&gt;
#[ http://www.softwarereality.com/lifecycle/xp/four_values.jsp Software Reality Four Values]&lt;br /&gt;
#[ http://repository.cmu.edu/cgi/viewcontent.cgi?article=1056&amp;amp;context=silicon_valley&amp;amp;sei-redir=1&amp;amp;referer=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3Dcompare%2520it%2520with%2520waterfall%2520model%2520and%2520extreme%2520programming%26source%3Dweb%26cd%3D2%26ved%3D0CCQQFjAB%26url%3Dhttp%253A%252F%252Frepository.cmu.edu%252Fcgi%252Fviewcontent.cgi%253Farticle%253D1056%2526context%253Dsilicon_valley%26ei%3DG_aCUKeIFo-k8gTJzIGQAw%26usg%3DAFQjCNEmwlV8Xg6uapysO7P0RTcnlEPz3g#search=%22compare%20waterfall%20model%20extreme%20programming%22 Comparing Extreme Programming and Waterfall Project Results]&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=67296</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=67296"/>
		<updated>2012-10-08T00:28:34Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Dynamic Finders */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a [http://en.wikipedia.org/wiki/Software_design_pattern Design pattern] in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through [http://en.wikipedia.org/wiki/Object-relational_mapping ORM] (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an [http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller MVC] application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on files, classes, tables etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
*lock_version.&lt;br /&gt;
*type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
*id - Reserved for primary keys.&lt;br /&gt;
*table_name_count - Reserved for counter cache.&lt;br /&gt;
*position - Reserved for acts_as_list. &lt;br /&gt;
*parent_id - Reserved for acts_as_tree.&lt;br /&gt;
*lft - Reserved for acts_as_nested_set.&lt;br /&gt;
*rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
*quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
*template.&lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
The Classes inheriting from ActiveRecord are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
===Create===&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
   User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
===Read===&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
   @user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
   @user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
   @all_users = User.all # Returns all the Users from the table&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
===Dynamic Finders===&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
   @my_user = User.find_by_name(“abc”)&lt;br /&gt;
   @my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
===Update===&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.name = “test”&lt;br /&gt;
   @my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
   @my_user = User.update(1, :name=”test3”)&lt;br /&gt;
   @result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Delete===&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
   # ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
   User.delete(1)&lt;br /&gt;
   User.delete([2,3,4,5])&lt;br /&gt;
   User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class, while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
The ActiveRecord connection adapter is meant to wrap and abstract away the underlying driver specific to database, and is meant to provide an interface which is common for database tasks such as creating and destroying databases, modifying tables, updating, deleting, and inserting data, managing transactions and running queries . The connection adapter is normally used internally by ActiveRecord but can be used without the help of ActiveRecord models as well.&lt;br /&gt;
&lt;br /&gt;
A connection adapter can be obtained in the following manner:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  object = Category.find(1)&lt;br /&gt;
  connection = object.connection&lt;br /&gt;
&lt;br /&gt;
Most applications connect to only one database which is defined in the database.yml file. In such a scenario every class which inherits from ActiveRecord::Base will be using the same connection. But in some special cases the application may also connect to a secondary database. That is the case in which some ActiveRecord classes connect to a secondary database. In such cases extra care need to take so that every class asks for a connection from the right database.&lt;br /&gt;
&lt;br /&gt;
Rails generally opens several connections at once, and these connections are managed in a pool. Each connection adapter object forms a single connection to some database. Connections can run only one SQL statement at a time, so generally one connection is opened per thread. When a job needs a connection to database, it checks out one of the pool which is returned when it finishes for use by another task.&lt;br /&gt;
&lt;br /&gt;
===Running Low-Level Queries===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord “model” objects are returned by most calls in the standard ActiveRecord API. There might be cases in which you want to bypass the overhead involved in creating full ActiveRecord objects, or maybe want to query data that does not have a corresponding ActiveRecord class. SQL queries can be written using the connection adapter's low-level query methods.&lt;br /&gt;
&lt;br /&gt;
In this first example, we get the “category_name” value from a single row in our “categoriess” table. If we only need the category name, we can grab the connection object and use the select_value method as shown below:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  category_name = connection.select_value(&amp;quot;SELECT name FROM categories WHERE id=1&amp;quot;)&lt;br /&gt;
  # =&amp;gt; &amp;quot;Football&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&lt;br /&gt;
Migrations help to version the various changes made to databases. It also allow developers to track a set of changes made to production or development databases and to rollback to a previous version if needed.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration User&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Specific commands can be written afterwards to create custom SQL. A model can also be created that comes with the migration.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model User name:string user_id:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The migration will generate a couple of new files under the &amp;quot;db&amp;quot; directory. The contents of such a generate file are as follows:&lt;br /&gt;
&lt;br /&gt;
  # 9889904091223123_create_user.rb&lt;br /&gt;
  class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :users do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :user_id&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :users&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;9889904091223123&amp;quot; at the beginning of the file-name is the timestamp. The timestamps will be different depending on the time of creation or modification of the database. This is helpful to rollback to a previous state if needed. This way the developer need not remember how the current state is reached and how to go back to a previous state.&lt;br /&gt;
&lt;br /&gt;
The ''self.up'' from the previous code snippet creates the User table and add the columns. The ''self.down'' method is used to drop the table and to remove all the contents. The ''self.up'' and ''self.down'' methods are necessary to keep the database consistent after a rollback.&lt;br /&gt;
&lt;br /&gt;
Rails adds an additional column called the &amp;quot;timestamps&amp;quot; to keep track of when each row was added. Rails also creates a primary key of the form &amp;quot;model_name&amp;quot;_id which increments automatically every time a row is added.&lt;br /&gt;
&lt;br /&gt;
Different types of datatypes can be used with ActiveRecord. Some of the most commonly used ones are:&lt;br /&gt;
&lt;br /&gt;
* integer&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* boolean&lt;br /&gt;
* references&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
&lt;br /&gt;
The migration file can be written into the database using the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above command will create the table and the various columns. This command can be used to migrate many files in one go. Connections between tables in the database can be introduced using references in the model.&lt;br /&gt;
&lt;br /&gt;
==Associations==&lt;br /&gt;
&lt;br /&gt;
Associations are used to connect two models. The association is used to describe the role of relations that models are having with each other. ActiveRecord associations can be used to describe one-to-one (1:1), one-to-many (1:n) and many-to-many (n:m) relationships between models. Associations are used to make common operations simpler and easier in your code. Rails supports six types of associations:&lt;br /&gt;
&lt;br /&gt;
* belongs_to&lt;br /&gt;
* has_one&lt;br /&gt;
* has_many&lt;br /&gt;
* has_many :through&lt;br /&gt;
* has_one :through&lt;br /&gt;
* has_and_belongs_to_many&lt;br /&gt;
&lt;br /&gt;
''belongs_to'' and ''has_one'' form a one-to-one relationship. ''has_one :through'' is a different way to create a one-to-one relationship. ''has_many'' and ''belongs_to'' form a one-to-many relation. ''has_and_belongs_to_many'' or an alternative way ''has_many :through'' to create a many-to-many relationship.&lt;br /&gt;
&lt;br /&gt;
===belongs_to Association===&lt;br /&gt;
&lt;br /&gt;
A ''belongs_to'' association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model. A ''belongs_to'' association can be used to setup a one-to-one or one-to-many relationship with other models. For example, consider a cookbook with recipes and categories such that each recipe &amp;quot;belongs to&amp;quot; a particular category.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one'' association is used to set up a one-to-one connection with another model such that each instance of a model contains one instance of another model. For example if we have two models User and Account, and each User has a single account, then we can use &amp;quot;has_one&amp;quot; to indicate the relationship between the two models.&lt;br /&gt;
&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one: account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many'' association is used to set up a one-to-may association with other models such that each instance has zero or more instances of another model. In the cookbook example, one category can have many recipes.&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many :through'' model is used to set up a many-to-many association with another model by going ''through'' a third model. In this case, the instance of a model can be connected to many instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. &lt;br /&gt;
&lt;br /&gt;
  class Physician &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :patients, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
  &lt;br /&gt;
  class Appointment &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :physician&lt;br /&gt;
    belongs_to :patient&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Patient &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :physicians, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one :through'' model is used to set up a one-to-one connection with another model by proceeding ''through'' a third model. In this case, the instance of a model can be connected to one instance of another model through a third model. For example, each client has one account, and each account has one account history.&lt;br /&gt;
&lt;br /&gt;
  class Client &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one :account&lt;br /&gt;
    has_one :account_history, :through =&amp;gt; :account&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :client&lt;br /&gt;
    has_one :account_history&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class AccountHistory &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_and_belongs_to_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_and_belongs_to_many'' association creates a many-to-many connection with another model without any model in between. In the cookbook example with recipe and category models, if the recipe is allowed to be in more than one category then the ''has_and_belongs_to_many'' association can be used.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many  :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
Active Record can be used to create the model layer for a web application and can be used to do the following tasks:&lt;br /&gt;
&lt;br /&gt;
* Create models for applications using the Rails script/generate script.&lt;br /&gt;
* Connect to database and use Rails migrations to create and modify the tables in the database.&lt;br /&gt;
* Search and find records in the database using a number of ActiveRecord methods.&lt;br /&gt;
* Update and delete rows or drop the tables in a database. &lt;br /&gt;
* Model database relations using ActiveRecord methods.&lt;br /&gt;
* Connect various models using associations.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
#[http://guides.rubyonrails.org Rails Guides]&lt;br /&gt;
#[http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord ActiveRecord - The Model]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Ruby ActiveRecord Pattern - Wikipedia]&lt;br /&gt;
#[http://www.developerfusion.com/article/84435/activerecord-for-ruby-and-rails/ Kevin Jones - ActiveRecord for Ruby and Rails]&lt;br /&gt;
#[http://www.daniel-azuma.com/blog/archives/216 Daniel Azuma - Setting the Database with ActiveRecord’s Connection API]&lt;br /&gt;
#Agile Web Development with Rails - Sam Ruby, Dave Thomas, David Hansson, 3rd Edition.&lt;br /&gt;
#Ruby on Rails Bible - Timothy Fisher&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=67295</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=67295"/>
		<updated>2012-10-08T00:25:28Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a [http://en.wikipedia.org/wiki/Software_design_pattern Design pattern] in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through [http://en.wikipedia.org/wiki/Object-relational_mapping ORM] (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an [http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller MVC] application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on files, classes, tables etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
*lock_version.&lt;br /&gt;
*type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
*id - Reserved for primary keys.&lt;br /&gt;
*table_name_count - Reserved for counter cache.&lt;br /&gt;
*position - Reserved for acts_as_list. &lt;br /&gt;
*parent_id - Reserved for acts_as_tree.&lt;br /&gt;
*lft - Reserved for acts_as_nested_set.&lt;br /&gt;
*rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
*quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
*template.&lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
The Classes inheriting from ActiveRecord are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
===Create===&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
   User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
===Read===&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
   @user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
   @user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
   @all_users = User.all # Returns all the Users from the table&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
===Dynamic Finders===&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
   @my_user = User.find_by_name(“abc”)&lt;br /&gt;
   @my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
===Update===&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.name = “test”&lt;br /&gt;
   @my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
   @my_user = User.update(1, :name=”test3”)&lt;br /&gt;
   @result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Delete===&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
   # ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
   User.delete(1)&lt;br /&gt;
   User.delete([2,3,4,5])&lt;br /&gt;
   User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class, while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
The ActiveRecord connection adapter is meant to wrap and abstract away the underlying driver specific to database, and is meant to provide an interface which is common for database tasks such as creating and destroying databases, modifying tables, updating, deleting, and inserting data, managing transactions and running queries . The connection adapter is normally used internally by ActiveRecord but can be used without the help of ActiveRecord models as well.&lt;br /&gt;
&lt;br /&gt;
A connection adapter can be obtained in the following manner:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  object = Category.find(1)&lt;br /&gt;
  connection = object.connection&lt;br /&gt;
&lt;br /&gt;
Most applications connect to only one database which is defined in the database.yml file. In such a scenario every class which inherits from ActiveRecord::Base will be using the same connection. But in some special cases the application may also connect to a secondary database. That is the case in which some ActiveRecord classes connect to a secondary database. In such cases extra care need to take so that every class asks for a connection from the right database.&lt;br /&gt;
&lt;br /&gt;
Rails generally opens several connections at once, and these connections are managed in a pool. Each connection adapter object forms a single connection to some database. Connections can run only one SQL statement at a time, so generally one connection is opened per thread. When a job needs a connection to database, it checks out one of the pool which is returned when it finishes for use by another task.&lt;br /&gt;
&lt;br /&gt;
===Running Low-Level Queries===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord “model” objects are returned by most calls in the standard ActiveRecord API. There might be cases in which you want to bypass the overhead involved in creating full ActiveRecord objects, or maybe want to query data that does not have a corresponding ActiveRecord class. SQL queries can be written using the connection adapter's low-level query methods.&lt;br /&gt;
&lt;br /&gt;
In this first example, we get the “category_name” value from a single row in our “categoriess” table. If we only need the category name, we can grab the connection object and use the select_value method as shown below:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  category_name = connection.select_value(&amp;quot;SELECT name FROM categories WHERE id=1&amp;quot;)&lt;br /&gt;
  # =&amp;gt; &amp;quot;Football&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&lt;br /&gt;
Migrations help to version the various changes made to databases. It also allow developers to track a set of changes made to production or development databases and to rollback to a previous version if needed.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration User&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Specific commands can be written afterwards to create custom SQL. A model can also be created that comes with the migration.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model User name:string user_id:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The migration will generate a couple of new files under the &amp;quot;db&amp;quot; directory. The contents of such a generate file are as follows:&lt;br /&gt;
&lt;br /&gt;
  # 9889904091223123_create_user.rb&lt;br /&gt;
  class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :users do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :user_id&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :users&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;9889904091223123&amp;quot; at the beginning of the file-name is the timestamp. The timestamps will be different depending on the time of creation or modification of the database. This is helpful to rollback to a previous state if needed. This way the developer need not remember how the current state is reached and how to go back to a previous state.&lt;br /&gt;
&lt;br /&gt;
The ''self.up'' from the previous code snippet creates the User table and add the columns. The ''self.down'' method is used to drop the table and to remove all the contents. The ''self.up'' and ''self.down'' methods are necessary to keep the database consistent after a rollback.&lt;br /&gt;
&lt;br /&gt;
Rails adds an additional column called the &amp;quot;timestamps&amp;quot; to keep track of when each row was added. Rails also creates a primary key of the form &amp;quot;model_name&amp;quot;_id which increments automatically every time a row is added.&lt;br /&gt;
&lt;br /&gt;
Different types of datatypes can be used with ActiveRecord. Some of the most commonly used ones are:&lt;br /&gt;
&lt;br /&gt;
* integer&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* boolean&lt;br /&gt;
* references&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
&lt;br /&gt;
The migration file can be written into the database using the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above command will create the table and the various columns. This command can be used to migrate many files in one go. Connections between tables in the database can be introduced using references in the model.&lt;br /&gt;
&lt;br /&gt;
==Associations==&lt;br /&gt;
&lt;br /&gt;
Associations are used to connect two models. The association is used to describe the role of relations that models are having with each other. ActiveRecord associations can be used to describe one-to-one (1:1), one-to-many (1:n) and many-to-many (n:m) relationships between models. Associations are used to make common operations simpler and easier in your code. Rails supports six types of associations:&lt;br /&gt;
&lt;br /&gt;
* belongs_to&lt;br /&gt;
* has_one&lt;br /&gt;
* has_many&lt;br /&gt;
* has_many :through&lt;br /&gt;
* has_one :through&lt;br /&gt;
* has_and_belongs_to_many&lt;br /&gt;
&lt;br /&gt;
''belongs_to'' and ''has_one'' form a one-to-one relationship. ''has_one :through'' is a different way to create a one-to-one relationship. ''has_many'' and ''belongs_to'' form a one-to-many relation. ''has_and_belongs_to_many'' or an alternative way ''has_many :through'' to create a many-to-many relationship.&lt;br /&gt;
&lt;br /&gt;
===belongs_to Association===&lt;br /&gt;
&lt;br /&gt;
A ''belongs_to'' association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model. A ''belongs_to'' association can be used to setup a one-to-one or one-to-many relationship with other models. For example, consider a cookbook with recipes and categories such that each recipe &amp;quot;belongs to&amp;quot; a particular category.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one'' association is used to set up a one-to-one connection with another model such that each instance of a model contains one instance of another model. For example if we have two models User and Account, and each User has a single account, then we can use &amp;quot;has_one&amp;quot; to indicate the relationship between the two models.&lt;br /&gt;
&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one: account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many'' association is used to set up a one-to-may association with other models such that each instance has zero or more instances of another model. In the cookbook example, one category can have many recipes.&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many :through'' model is used to set up a many-to-many association with another model by going ''through'' a third model. In this case, the instance of a model can be connected to many instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. &lt;br /&gt;
&lt;br /&gt;
  class Physician &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :patients, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
  &lt;br /&gt;
  class Appointment &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :physician&lt;br /&gt;
    belongs_to :patient&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Patient &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :physicians, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one :through'' model is used to set up a one-to-one connection with another model by proceeding ''through'' a third model. In this case, the instance of a model can be connected to one instance of another model through a third model. For example, each client has one account, and each account has one account history.&lt;br /&gt;
&lt;br /&gt;
  class Client &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one :account&lt;br /&gt;
    has_one :account_history, :through =&amp;gt; :account&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :client&lt;br /&gt;
    has_one :account_history&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class AccountHistory &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_and_belongs_to_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_and_belongs_to_many'' association creates a many-to-many connection with another model without any model in between. In the cookbook example with recipe and category models, if the recipe is allowed to be in more than one category then the ''has_and_belongs_to_many'' association can be used.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many  :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
Active Record can be used to create the model layer for a web application and can be used to do the following tasks:&lt;br /&gt;
&lt;br /&gt;
* Create models for applications using the Rails script/generate script.&lt;br /&gt;
* Connect to database and use Rails migrations to create and modify the tables in the database.&lt;br /&gt;
* Search and find records in the database using a number of ActiveRecord methods.&lt;br /&gt;
* Update and delete rows or drop the tables in a database. &lt;br /&gt;
* Model database relations using ActiveRecord methods.&lt;br /&gt;
* Connect various models using associations.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
#[http://guides.rubyonrails.org Rails Guides]&lt;br /&gt;
#[http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord ActiveRecord - The Model]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Ruby ActiveRecord Pattern - Wikipedia]&lt;br /&gt;
#[http://www.developerfusion.com/article/84435/activerecord-for-ruby-and-rails/ Kevin Jones - ActiveRecord for Ruby and Rails]&lt;br /&gt;
#[http://www.daniel-azuma.com/blog/archives/216 Daniel Azuma - Setting the Database with ActiveRecord’s Connection API]&lt;br /&gt;
#Agile Web Development with Rails - Sam Ruby, Dave Thomas, David Hansson, 3rd Edition.&lt;br /&gt;
#Ruby on Rails Bible - Timothy Fisher&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66813</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66813"/>
		<updated>2012-10-04T00:09:37Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Naming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on files, classes, tables etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
*lock_version.&lt;br /&gt;
*type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
*id - Reserved for primary keys.&lt;br /&gt;
*table_name_count - Reserved for counter cache.&lt;br /&gt;
*position - Reserved for acts_as_list. &lt;br /&gt;
*parent_id - Reserved for acts_as_tree.&lt;br /&gt;
*lft - Reserved for acts_as_nested_set.&lt;br /&gt;
*rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
*quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
*template.&lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
The Classes inheriting from ActiveRecord are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Create===&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
   User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
===Read===&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
   @user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
   @user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
   @all_users = User.all # Returns all the Users from the table&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
===Dynamic Finders===&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
   @my_user = User.find_by_name(“abc”)&lt;br /&gt;
   @my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
===Update===&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.name = “test”&lt;br /&gt;
   @my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
   @my_user = User.update(1, :name=”test3”)&lt;br /&gt;
   @result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Delete===&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
   # ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
   User.delete(1)&lt;br /&gt;
   User.delete([2,3,4,5])&lt;br /&gt;
   User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class, while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
The ActiveRecord connection adapter is meant to wrap and abstract away the underlying driver specific to database, and is meant to provide an interface which is common for database tasks such as creating and destroying databases, modifying tables, updating, deleting, and inserting data, managing transactions and running queries . The connection adapter is normally used internally by ActiveRecord but can be used without the help of ActiveRecord models as well.&lt;br /&gt;
&lt;br /&gt;
A connection adapter can be obtained in the following manner:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  object = Category.find(1)&lt;br /&gt;
  connection = object.connection&lt;br /&gt;
&lt;br /&gt;
Most applications connect to only one database which is defined in the database.yml file. In such a scenario every class which inherits from ActiveRecord::Base will be using the same connection. But in some special cases the application may also connect to a secondary database. That is the case in which some ActiveRecord classes connect to a secondary database. In such cases extra care need to take so that every class asks for a connection from the right database.&lt;br /&gt;
&lt;br /&gt;
Rails generally opens several connections at once, and these connections are managed in a pool. Each connection adapter object forms a single connection to some database. Connections can run only one SQL statement at a time, so generally one connection is opened per thread. When a job needs a connection to database, it checks out one of the pool which is returned when it finishes for use by another task.&lt;br /&gt;
&lt;br /&gt;
===Running Low-Level Queries===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord “model” objects are returned by ost calls in the standard ActiveRecord API. There might be cases in which you want to bypass the overhead involved in creating full ActiveRecord objects, or maybe want to query data that does not have a corresponding ActiveRecord class. SQL queries can be written using the connection adapter's low-level query methods.&lt;br /&gt;
&lt;br /&gt;
In this first example, we get the “category_name” value from a single row in our “categoriess” table. If we only need the category name, we can grab the connection object and use the select_value method as shown below:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  category_name = connection.select_value(&amp;quot;SELECT name FROM categories WHERE id=1&amp;quot;)&lt;br /&gt;
  # =&amp;gt; &amp;quot;Football&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&lt;br /&gt;
Migrations help to version the various changes made to databases. It also allow developers to track a set of changes made to production or development databases and to rollback to a previous version if needed.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration User&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Specific commands can be written afterwards to create custom SQL. A model can also be created that comes with the migration.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model User name:string user_id:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The migration will generate a couple of new files under the &amp;quot;db&amp;quot; directory. The contents of such a generate file are as follows:&lt;br /&gt;
&lt;br /&gt;
  # 9889904091223123_create_user.rb&lt;br /&gt;
  class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :users do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :user_id&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :users&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;9889904091223123&amp;quot; at the beginning of the file-name is the timestamp. The timestamps will be different depending on the time of creation or modification of the database. This is helpful to rollback to a previous state if needed. This way the developer need not remember how the current state is reached and how to go back to a previous state.&lt;br /&gt;
&lt;br /&gt;
The ''self.up'' from the previous code snippet creates the User table and add the columns. The ''self.down'' method is used to drop the table and to remove all the contents. The ''self.up'' and ''self.down'' methods are necessary to keep the database consistent after a rollback.&lt;br /&gt;
&lt;br /&gt;
Rails adds an additional column called the &amp;quot;timestamps&amp;quot; to keep track of when each row was added. Rails also creates a primary key of the form &amp;quot;model_name&amp;quot;_id which increments automatically every time a row is added.&lt;br /&gt;
&lt;br /&gt;
Different types of datatypes can be used with ActiveRecord. Some of the most commonly used ones are:&lt;br /&gt;
&lt;br /&gt;
* integer&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* boolean&lt;br /&gt;
* references&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
&lt;br /&gt;
The migration file can be written into the database using the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above command will create the table and the various columns. This command can be used to migrate many files in one go. Connections between tables in the database can be introduced using references in the model.&lt;br /&gt;
&lt;br /&gt;
==Associations==&lt;br /&gt;
&lt;br /&gt;
Associations are used to connect two models. The association is used to describe the role of relations that models are having with each other. ActiveRecord associations can be used to describe one-to-one (1:1), one-to-many (1:n) and many-to-many (n:m) relationships between models. Associations are used to make common operations simpler and easier in your code. Rails supports six types of associations:&lt;br /&gt;
&lt;br /&gt;
* belongs_to&lt;br /&gt;
* has_one&lt;br /&gt;
* has_many&lt;br /&gt;
* has_many :through&lt;br /&gt;
* has_one :through&lt;br /&gt;
* has_and_belongs_to_many&lt;br /&gt;
&lt;br /&gt;
''belongs_to'' and ''has_one'' form a one-to-one relationship. ''has_one :through'' is a different way to create a one-to-one relationship. ''has_many'' and ''belongs_to'' form a one-to-many relation. ''has_and_belongs_to_many'' or an alternative way ''has_many :through'' to create a many-to-many relationship.&lt;br /&gt;
&lt;br /&gt;
===belongs_to Association===&lt;br /&gt;
&lt;br /&gt;
A ''belongs_to'' association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model. A ''belongs_to'' association can be used to setup a one-to-one or one-to-many relationship with other models. For example, consider a cookbook with recipes and categories such that each recipe &amp;quot;belongs to&amp;quot; a particular category.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one'' association is used to set up a one-to-one connection with another model such that each instance of a model contains one instance of another model. For example if we have two models User and Account, and each User has a single account, then we can use &amp;quot;has_one&amp;quot; to indicate the relationship between the two models.&lt;br /&gt;
&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one: account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many'' association is used to set up a one-to-may association with other models such that each instance has zero or more instances of another model. In the cookbook example, one category can have many recipes.&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many :through'' model is used to set up a many-to-many association with another model by going ''through'' a third model. In this case, the instance of a model can be connected to many instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. &lt;br /&gt;
&lt;br /&gt;
  class Physician &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :patients, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
  &lt;br /&gt;
  class Appointment &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :physician&lt;br /&gt;
    belongs_to :patient&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Patient &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :physicians, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one :through'' model is used to set up a one-to-one connection with another model by proceeding ''through'' a third model. In this case, the instance of a model can be connected to one instance of another model through a third model. For example, each client has one account, and each account has one account history.&lt;br /&gt;
&lt;br /&gt;
  class Client &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one :account&lt;br /&gt;
    has_one :account_history, :through =&amp;gt; :account&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :client&lt;br /&gt;
    has_one :account_history&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class AccountHistory &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_and_belongs_to_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_and_belongs_to_many'' association creates a many-to-many connection with another model without any model in between. In the cookbook example with recipe and category models, if the recipe is allowed to be in more than one category then the ''has_and_belongs_to_many'' association can be used.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many  :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
Active Record can be used to create the model layer for a web application and can be used to do the following tasks:&lt;br /&gt;
&lt;br /&gt;
* Create models for applications using the Rails script/generate script.&lt;br /&gt;
* Connect to database and use Rails migrations to create and modify the database.&lt;br /&gt;
* Search and find records in the database using a number of ActiveRecord methods.&lt;br /&gt;
* Update and delete rows or drop the tables in a database. &lt;br /&gt;
* Model database relations using ActiveRecord methods.&lt;br /&gt;
* Connect various models using associations.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
#[http://guides.rubyonrails.org Rails Guides]&lt;br /&gt;
#[http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord ActiveRecord - The Model]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Ruby ActiveRecord Pattern - Wikipedia]&lt;br /&gt;
#[http://www.developerfusion.com/article/84435/activerecord-for-ruby-and-rails/ Kevin Jones - ActiveRecord for Ruby and Rails]&lt;br /&gt;
#[http://www.daniel-azuma.com/blog/archives/216 Daniel Azuma - Setting the Database with ActiveRecord’s Connection API]&lt;br /&gt;
#Agile Web Development with Rails - Sam Ruby, Dave Thomas, David Hansson, 3rd Edition.&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66804</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66804"/>
		<updated>2012-10-04T00:06:20Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
*lock_version.&lt;br /&gt;
*type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
*id - Reserved for primary keys.&lt;br /&gt;
*table_name_count - Reserved for counter cache.&lt;br /&gt;
*position - Reserved for acts_as_list. &lt;br /&gt;
*parent_id - Reserved for acts_as_tree.&lt;br /&gt;
*lft - Reserved for acts_as_nested_set.&lt;br /&gt;
*rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
*quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
*template.&lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Create===&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
   User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
===Read===&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
   @user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
   @user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
   @all_users = User.all # Returns all the Users from the table&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
===Dynamic Finders===&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
   @my_user = User.find_by_name(“abc”)&lt;br /&gt;
   @my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
===Update===&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.name = “test”&lt;br /&gt;
   @my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
   @my_user = User.update(1, :name=”test3”)&lt;br /&gt;
   @result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Delete===&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
   # ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
   User.delete(1)&lt;br /&gt;
   User.delete([2,3,4,5])&lt;br /&gt;
   User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class, while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
The ActiveRecord connection adapter is meant to wrap and abstract away the underlying driver specific to database, and is meant to provide an interface which is common for database tasks such as creating and destroying databases, modifying tables, updating, deleting, and inserting data, managing transactions and running queries . The connection adapter is normally used internally by ActiveRecord but can be used without the help of ActiveRecord models as well.&lt;br /&gt;
&lt;br /&gt;
A connection adapter can be obtained in the following manner:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  object = Category.find(1)&lt;br /&gt;
  connection = object.connection&lt;br /&gt;
&lt;br /&gt;
Most applications connect to only one database which is defined in the database.yml file. In such a scenario every class which inherits from ActiveRecord::Base will be using the same connection. But in some special cases the application may also connect to a secondary database. That is the case in which some ActiveRecord classes connect to a secondary database. In such cases extra care need to take so that every class asks for a connection from the right database.&lt;br /&gt;
&lt;br /&gt;
Rails generally opens several connections at once, and these connections are managed in a pool. Each connection adapter object forms a single connection to some database. Connections can run only one SQL statement at a time, so generally one connection is opened per thread. When a job needs a connection to database, it checks out one of the pool which is returned when it finishes for use by another task.&lt;br /&gt;
&lt;br /&gt;
===Running Low-Level Queries===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord “model” objects are returned by ost calls in the standard ActiveRecord API. There might be cases in which you want to bypass the overhead involved in creating full ActiveRecord objects, or maybe want to query data that does not have a corresponding ActiveRecord class. SQL queries can be written using the connection adapter's low-level query methods.&lt;br /&gt;
&lt;br /&gt;
In this first example, we get the “category_name” value from a single row in our “categoriess” table. If we only need the category name, we can grab the connection object and use the select_value method as shown below:&lt;br /&gt;
&lt;br /&gt;
  connection = Category.connection&lt;br /&gt;
  category_name = connection.select_value(&amp;quot;SELECT name FROM categories WHERE id=1&amp;quot;)&lt;br /&gt;
  # =&amp;gt; &amp;quot;Football&amp;quot;&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&lt;br /&gt;
Migrations help to version the various changes made to databases. It also allow developers to track a set of changes made to production or development databases and to rollback to a previous version if needed.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration User&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Specific commands can be written afterwards to create custom SQL. A model can also be created that comes with the migration.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model User name:string user_id:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The migration will generate a couple of new files under the &amp;quot;db&amp;quot; directory. The contents of such a generate file are as follows:&lt;br /&gt;
&lt;br /&gt;
  # 9889904091223123_create_user.rb&lt;br /&gt;
  class CreateUsers &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :users do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :user_id&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :users&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
The &amp;quot;9889904091223123&amp;quot; at the beginning of the file-name is the timestamp. The timestamps will be different depending on the time of creation or modification of the database. This is helpful to rollback to a previous state if needed. This way the developer need not remember how the current state is reached and how to go back to a previous state.&lt;br /&gt;
&lt;br /&gt;
The ''self.up'' from the previous code snippet creates the User table and add the columns. The ''self.down'' method is used to drop the table and to remove all the contents. The ''self.up'' and ''self.down'' methods are necessary to keep the database consistent after a rollback.&lt;br /&gt;
&lt;br /&gt;
Rails adds an additional column called the &amp;quot;timestamps&amp;quot; to keep track of when each row was added. Rails also creates a primary key of the form &amp;quot;model_name&amp;quot;_id which increments automatically every time a row is added.&lt;br /&gt;
&lt;br /&gt;
Different types of datatypes can be used with ActiveRecord. Some of the most commonly used ones are:&lt;br /&gt;
&lt;br /&gt;
* integer&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* boolean&lt;br /&gt;
* references&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
&lt;br /&gt;
The migration file can be written into the database using the following command:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above command will create the table and the various columns. This command can be used to migrate many files in one go. Connections between tables in the database can be introduced using references in the model.&lt;br /&gt;
&lt;br /&gt;
==Associations==&lt;br /&gt;
&lt;br /&gt;
Associations are used to connect two models. The association is used to describe the role of relations that models are having with each other. ActiveRecord associations can be used to describe one-to-one (1:1), one-to-many (1:n) and many-to-many (n:m) relationships between models. Associations are used to make common operations simpler and easier in your code. Rails supports six types of associations:&lt;br /&gt;
&lt;br /&gt;
* belongs_to&lt;br /&gt;
* has_one&lt;br /&gt;
* has_many&lt;br /&gt;
* has_many :through&lt;br /&gt;
* has_one :through&lt;br /&gt;
* has_and_belongs_to_many&lt;br /&gt;
&lt;br /&gt;
''belongs_to'' and ''has_one'' form a one-to-one relationship. ''has_one :through'' is a different way to create a one-to-one relationship. ''has_many'' and ''belongs_to'' form a one-to-many relation. ''has_and_belongs_to_many'' or an alternative way ''has_many :through'' to create a many-to-many relationship.&lt;br /&gt;
&lt;br /&gt;
===belongs_to Association===&lt;br /&gt;
&lt;br /&gt;
A ''belongs_to'' association sets up a one-to-one connection with another model, such that each instance of the declaring model “belongs to” one instance of the other model. A ''belongs_to'' association can be used to setup a one-to-one or one-to-many relationship with other models. For example, consider a cookbook with recipes and categories such that each recipe &amp;quot;belongs to&amp;quot; a particular category.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one'' association is used to set up a one-to-one connection with another model such that each instance of a model contains one instance of another model. For example if we have two models User and Account, and each User has a single account, then we can use &amp;quot;has_one&amp;quot; to indicate the relationship between the two models.&lt;br /&gt;
&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one: account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many'' association is used to set up a one-to-may association with other models such that each instance has zero or more instances of another model. In the cookbook example, one category can have many recipes.&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_many :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_many :through'' model is used to set up a many-to-many association with another model by going ''through'' a third model. In this case, the instance of a model can be connected to many instances of another model by proceeding through a third model. For example, consider a medical practice where patients make appointments to see physicians. &lt;br /&gt;
&lt;br /&gt;
  class Physician &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :patients, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
  &lt;br /&gt;
  class Appointment &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :physician&lt;br /&gt;
    belongs_to :patient&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Patient &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_many :appointments&lt;br /&gt;
    has_many :physicians, :through =&amp;gt; :appointments&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_one :through Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_one :through'' model is used to set up a one-to-one connection with another model by proceeding ''through'' a third model. In this case, the instance of a model can be connected to one instance of another model through a third model. For example, each client has one account, and each account has one account history.&lt;br /&gt;
&lt;br /&gt;
  class Client &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_one :account&lt;br /&gt;
    has_one :account_history, :through =&amp;gt; :account&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :client&lt;br /&gt;
    has_one :account_history&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  class AccountHistory &amp;lt; ActiveRecord::Base&lt;br /&gt;
    belongs_to :account&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
===has_and_belongs_to_many Association===&lt;br /&gt;
&lt;br /&gt;
A ''has_and_belongs_to_many'' association creates a many-to-many connection with another model without any model in between. In the cookbook example with recipe and category models, if the recipe is allowed to be in more than one category then the ''has_and_belongs_to_many'' association can be used.&lt;br /&gt;
&lt;br /&gt;
  class Recipe &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many :category&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  class Category &amp;lt; ActiveRecord::Base&lt;br /&gt;
    has_and_belongs_to_many  :recipes&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
==Conclusion==&lt;br /&gt;
&lt;br /&gt;
Active Record can be used to create the model layer for a web application and can be used to do the following tasks:&lt;br /&gt;
&lt;br /&gt;
* Create models for applications using the Rails script/generate script.&lt;br /&gt;
* Connect to database and use Rails migrations to create and modify the database.&lt;br /&gt;
* Search and find records in the database using a number of ActiveRecord methods.&lt;br /&gt;
* Update and delete rows or drop the tables in a database. &lt;br /&gt;
* Model database relations using ActiveRecord methods.&lt;br /&gt;
* Connect various models using associations.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
#[http://guides.rubyonrails.org Rails Guides]&lt;br /&gt;
#[http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord ActiveRecord - The Model]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Ruby ActiveRecord Pattern - Wikipedia]&lt;br /&gt;
#[http://www.developerfusion.com/article/84435/activerecord-for-ruby-and-rails/ Kevin Jones - ActiveRecord for Ruby and Rails]&lt;br /&gt;
#[http://www.daniel-azuma.com/blog/archives/216 Daniel Azuma - Setting the Database with ActiveRecord’s Connection API]&lt;br /&gt;
#Agile Web Development with Rails - Sam Ruby, Dave Thomas, David Hansson, 3rd Edition.&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66305</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66305"/>
		<updated>2012-10-03T04:22:41Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
*lock_version.&lt;br /&gt;
*type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
*id - Reserved for primary keys.&lt;br /&gt;
*table_name_count - Reserved for counter cache.&lt;br /&gt;
*position - Reserved for acts_as_list. &lt;br /&gt;
*parent_id - Reserved for acts_as_tree.&lt;br /&gt;
*lft - Reserved for acts_as_nested_set.&lt;br /&gt;
*rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
*quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
*template.&lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
   User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
   @user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
   @user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
   @all_users = User.all # Returns all the Users from the table&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
   @my_user = User.find_by_name(“abc”)&lt;br /&gt;
   @my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.name = “test”&lt;br /&gt;
   @my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
   @my_user = User.update(1, :name=”test3”)&lt;br /&gt;
   @result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
   @my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
   @my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
   # ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
   User.delete(1)&lt;br /&gt;
   User.delete([2,3,4,5])&lt;br /&gt;
   User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class, while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
This is important because of the below mentioned details.&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. &lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
  create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66291</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66291"/>
		<updated>2012-10-03T04:08:29Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Reserved names and Attributes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
*lock_version.&lt;br /&gt;
*type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
*id - Reserved for primary keys.&lt;br /&gt;
*table_name_count - Reserved for counter cache.&lt;br /&gt;
*position - Reserved for acts_as_list. &lt;br /&gt;
*parent_id - Reserved for acts_as_tree.&lt;br /&gt;
*lft - Reserved for acts_as_nested_set.&lt;br /&gt;
*rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
*quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
*template.&lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
This is important because of the below mentioned details.&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. &lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66282</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66282"/>
		<updated>2012-10-03T04:01:34Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66281</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66281"/>
		<updated>2012-10-03T04:01:14Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Create */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Create&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66280</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66280"/>
		<updated>2012-10-03T04:00:43Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Create ==&lt;br /&gt;
 &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66278</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66278"/>
		<updated>2012-10-03T03:59:38Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
  create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66276</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66276"/>
		<updated>2012-10-03T03:58:44Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66271</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66271"/>
		<updated>2012-10-03T03:58:09Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
[[3.1 Create]]&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66267</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66267"/>
		<updated>2012-10-03T03:57:30Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
&lt;br /&gt;
A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66265</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66265"/>
		<updated>2012-10-03T03:56:59Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* 3 CRUD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
 A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66263</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66263"/>
		<updated>2012-10-03T03:56:35Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Table Naming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== 3 CRUD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
 CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
 A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
[edit] Connecting to the Database&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66257</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66257"/>
		<updated>2012-10-03T03:54:25Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Table Naming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
  &amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
  # 20090409120944_create_categories.rb&lt;br /&gt;
  class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
    def self.up&lt;br /&gt;
      create_table :categories do |t|&lt;br /&gt;
        t.string :name&lt;br /&gt;
        t.integer :amount&lt;br /&gt;
&lt;br /&gt;
        t.timestamps&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    def self.down&lt;br /&gt;
      drop_table :categories&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
  &amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66254</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66254"/>
		<updated>2012-10-03T03:53:24Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* Table Naming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 20px&amp;quot;&amp;gt;'''Active Records'''&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
==Naming==&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
===Reserved names and Attributes===&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
===Class Naming===&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
===Table Naming===&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
&lt;br /&gt;
 CRUD stands for 'Create', 'Read' , 'Update' and 'Delete'. These are the four basic operations which are generally performed on tables in a database. The ActiveRecord module provides predefined methods for the basic CRUD operations for the model.&lt;br /&gt;
&lt;br /&gt;
3.1 Create&lt;br /&gt;
 A new record can be created in the table by invoking the “save” function on the model object whose record has to be created in the database. ActiveRecord will use the Object's attributes as the field values for the record. The data is not persisted in the database until we call the save function. &lt;br /&gt;
&lt;br /&gt;
   @user = User.new&lt;br /&gt;
   @user.name = “abc”&lt;br /&gt;
   @user.age = 23&lt;br /&gt;
   @user.save      #returns a boolean indicating whether the save was successful or not (whether a new record was created or not)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
ActiveRecord provides another convinient way to create a new record without creating instantiating the model explicitly and then using “save”.   To do this, we use the 'create' function. By default the primary key used in the table is “id” which is generated automatically.&lt;br /&gt;
&lt;br /&gt;
    User.create(:name=&amp;gt;”xyz”, :age=”23”)&lt;br /&gt;
&lt;br /&gt;
3.2 Read&lt;br /&gt;
&lt;br /&gt;
A record can be read from the table by using the various functions like “find” (find the model record by specifying a value used in its primary key),  “where”, “all” , “first” and “last”.  All these functions instantiate a new Object for the model and populate its attributes using the fields of the record.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@user_first = User.first #Finds and returns the 1st User from the table&lt;br /&gt;
&lt;br /&gt;
	@user_last = User.last #Finds and returns the Last User from the table&lt;br /&gt;
&lt;br /&gt;
	@all_users = User.all # Returns all the Users from the table&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
&lt;br /&gt;
	@my_other_user = User.where(:name=&amp;gt;”abc”) #Finds and returns the user whose “name” is “abc” .&lt;br /&gt;
&lt;br /&gt;
Dynamic Finders&lt;br /&gt;
&lt;br /&gt;
Some of the most common searchs performed on databases are to return the rows where a column matches a given value. In many other languages and frameworks, we would generally need to construct SQL queries to perform these searches. ActiveRecord uses Ruby’s dynamic power to do this for us.&lt;br /&gt;
&lt;br /&gt;
For example, our User model has attributes such as name and age. We can use these names in finder methods to return rows where the corresponding columns match some value:&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find_by_name(“abc”)&lt;br /&gt;
	@my_user = User.find_by_age(15)&lt;br /&gt;
&lt;br /&gt;
3.3 Update&lt;br /&gt;
&lt;br /&gt;
A record in the table corresponding to a given model instance can be Updated by using the function “save”. &lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.name = “test”&lt;br /&gt;
	@my_user.save&lt;br /&gt;
&lt;br /&gt;
Moreover, we can combine the functions of reading a row and updating it using the class methods update and update_all. The update method takes an id parameter and a set of attributes. It fetches the corresponding row, updates the given attributes, saves the result to the database, and returns the model object.&lt;br /&gt;
	&lt;br /&gt;
	@my_user = User.update(1, :name=”test3”)&lt;br /&gt;
	@result = User.update_all(“age= age+1”)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
3.4 Delete&lt;br /&gt;
&lt;br /&gt;
A record can be deleted from the table by invoking the “destroy” functionality on the instance of the object.&lt;br /&gt;
The destroy instance method deletes from the database the row corresponding to a particular model object. It then freezes the contents of that object, preventing future changes to the attributes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
	@my_user = User.find(5) #Finds and returns the record from the users table whose id = 5&lt;br /&gt;
	@my_user.destroy # deletes the record corresponding to the user with id = 5 from the table&lt;br /&gt;
	# ... my_user is now frozen&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
It also has two class-level methods, delete and delete_all. The delete method takes a single id or an array of ids and deletes the corresponding row(s) in the underlying table. delete_all deletes rows matching a given condition. &lt;br /&gt;
User.delete(1)&lt;br /&gt;
User.delete([2,3,4,5])&lt;br /&gt;
User.delete_all([&amp;quot;age &amp;lt; ?&amp;quot; , 18])&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The “delete” methods bypass the ActiveRecord callback and validation functions that may be defined for the model class,&lt;br /&gt;
while the “destroy” methods ensure that they are all invoked. Hence, it is better to use the “destroy” methods as it ensures that our database is as per the business rules defined in the model.&lt;br /&gt;
&lt;br /&gt;
==Connecting to the Database==&lt;br /&gt;
&lt;br /&gt;
Hidden underneath ActiveRecord class is a useful low-level object called the ActiveRecord connection adapter. It wraps and abstracts away the underlying database-specific driver, and provides a common interface for database tasks such as creating and destroying databases, creating and modifying tables, inserting, updating, and deleting data, running queries, and managing transactions. Normally, the connection adapter is used internally by ActiveRecord, but can be accessed yourself if you want to talk to the database directly without using ActiveRecord “models.”&lt;br /&gt;
&lt;br /&gt;
To obtain a connection adapter object, simply call the connection method on your ActiveRecord class or any ActiveRecord object:&lt;br /&gt;
&lt;br /&gt;
  connection = User.connection&lt;br /&gt;
  obj = User.find(1)&lt;br /&gt;
  connection = obj.connection&lt;br /&gt;
&lt;br /&gt;
In most Rails applications, you talk to just one database, as defined in the database.yml file. For such an application, every ActiveRecord class, including ActiveRecord::Base, will give you the same connection. So in those cases, it doesn’t matter which class you use. However, if the Rails application connects to a secondary database for some ActiveRecord classes (using the establish_connection method) then those classes will yield a connection object pointing at the secondary database. In those cases, you will need to pay attention to which database you need to talk to, and ask for a connection from the right class.&lt;br /&gt;
&lt;br /&gt;
Each connection adapter object represents a single connection to a database. Rails generally opens several connections at once and manages them in a connection pool. When a task needs a database connection, it checks one out of the pool; when it finishes, it checks the connection back in so that the next task can use it. Connections can run only one SQL statement at a time, so generally one connection is opened per thread.&lt;br /&gt;
&lt;br /&gt;
==Migrations==&lt;br /&gt;
&amp;lt;ref&amp;gt;'''Excerpts modified and republished from Steve Eichert's [http://www.emxsoftware.com/RubyOnRails/Ruby+on+Rails+Migrations+Explained Ruby on rails Migrations Explained] article.'''&amp;lt;/ref&amp;gt; Migrations meant to solve the problem of rolling out changes to your database.  By defining the changes to your database schema in Ruby files, development teams can ensure that all changes to the database are properly versioned.  Additionally migrations help to ensure that rolling out changes to fellow developers as well as other servers (development, QA, production) is handled in a consistent and manageable fashion.&lt;br /&gt;
&lt;br /&gt;
=== Building a Migration ===&lt;br /&gt;
You can either build the migration on its own using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate migration Category&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and write the specific commands afterwards (if you want to create custom SQL, this is the way to go) or you can create a model that comes with the migration using&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Category name:string amount:integer&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The console tells you that there were some files created and some already existent. As mentioned before, Rails will never overwrite existing files unless stated otherwise.&lt;br /&gt;
&lt;br /&gt;
Now lets take a look at the migration&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
# 20090409120944_create_categories.rb&lt;br /&gt;
class CreateCategories &amp;lt; ActiveRecord::Migration&lt;br /&gt;
  def self.up&lt;br /&gt;
    create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
&lt;br /&gt;
      t.timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down&lt;br /&gt;
    drop_table :categories&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
First of all, take a look at the number (''20090409120944'') in front of your file. This is the timestamp of your file and important for the creation of the database tables. This timestamp will always be different, depending on the exact time of the creation of your migration. The idea behind this is to have a &amp;quot;history&amp;quot; of all your migrations available.&lt;br /&gt;
&lt;br /&gt;
But why is this important?&lt;br /&gt;
&lt;br /&gt;
Imagine that you work on a Rails project and you create tables, alter columns or remove columns from your database via migrations. After some time, your client changes his mind and he wants only very basic features and you already started to create advanced features and altered the database. Because you can't remember all the changes that went into the database and their order, you will either spend a lot of time working on the database to have the &amp;quot;old&amp;quot; state available or you have to start from scratch because it would take too long to remember and redo all changes.&lt;br /&gt;
This is where migration come in handy, because of the timestamp, Rails is able to recognize the changes in their actual order and all changes can be undone easily. Never alter the timestamp manually. This will certainly cause problems. For more on those topic, check out the &amp;quot;[[Ruby_on_Rails/ActiveRecord/Migrations#Managing_Migrations |managing migrations]]&amp;quot; section&lt;br /&gt;
&lt;br /&gt;
Speaking of undoing and redoing: notice the two methods inside your migration &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt;. Both of them do exactly the opposite of each other. While &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; creates our categories table with all columns, &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; removes (drops) the table from the database with all its contents(!!). When Rails sees that the migration has not been moved to the database, it will use the &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; method, if you undo the migration, the &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method gets executed. This way you can make sure that you will always be able to go back to a past state of your database. Keep in mind when writing own migrations always include a &amp;lt;tt&amp;gt;self.up&amp;lt;/tt&amp;gt; and a &amp;lt;tt&amp;gt;self.down&amp;lt;/tt&amp;gt; method to assure that the database state will be consistent after an rollback.&lt;br /&gt;
&lt;br /&gt;
OK, let's start with the migration itself:&lt;br /&gt;
&amp;lt;source lang=rails&amp;gt;&lt;br /&gt;
create_table :categories do |t|&lt;br /&gt;
      t.string :name&lt;br /&gt;
      t.integer :amount&lt;br /&gt;
      t.timestamps&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/source&amp;gt;&lt;br /&gt;
&lt;br /&gt;
We want to create a table called categories(&amp;lt;tt&amp;gt;create_table :categories&amp;lt;/tt&amp;gt;) that has a name and an amount column. Additionally Rails adds an timestamp for us where it will store the creation date and the update date for each row. Rails will also create an primary key called '''model'''_id that auto-increments (1,2,3,...) with every row.&lt;br /&gt;
&lt;br /&gt;
You can choose from a variety of datatypes that go with ActiveRecord. The most common types are:&lt;br /&gt;
&lt;br /&gt;
* string&lt;br /&gt;
* text&lt;br /&gt;
* integer&lt;br /&gt;
* decimal&lt;br /&gt;
* timestamp&lt;br /&gt;
* references&lt;br /&gt;
* boolean&lt;br /&gt;
&lt;br /&gt;
But wait, there is not yet a single table nor column in our database. We need to write the migration file into the database.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
handles this job. The command is able to create the table and all the necessary columns inside the table. This command is not limited to migrating a single file so you can migrate an unlimited number of files at once. Rake also knows what migrations are already in the database so it won't overwrite your tables. For more info see &amp;quot;Managing Migrations&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
To add a connection between your tables we want to add references in our model. References are comparable to foreign keys (Rails doesn't use foreign keys by default because not all databases can handle foreign keys but you can write custom SQL to make use of foreign keys) and tell your table where to look for further data.&lt;br /&gt;
&lt;br /&gt;
Let's add another model to our already existent database. We want to create a category that has multiple products. So we need to reference this product in our category. We want to create a model:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;ruby script/generate model Products name:string category:references&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and insert it into the database&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;rake db:migrate&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the type :references for the category. This tells Rails to create a column inside the database that holds a reference to our category. Inside our database there is now a &amp;lt;tt&amp;gt;category_id&amp;lt;/tt&amp;gt; column for our product. (In order to work with these two models, we need to add associations inside our models, see Associations)&lt;br /&gt;
&lt;br /&gt;
===Managing Migrations===&lt;br /&gt;
We already talked about how migrations can help you to organise your database in a very convenient manner. Now we will take a look at how this is achieved. You already know that the timestamp in the filename tells rails when the migration was created and Rake know what migrations are already inside the database.&lt;br /&gt;
&lt;br /&gt;
To restore the state of the database as it was, say 5 migrations before the current, we can use&lt;br /&gt;
  $rake db:rollback STEP=5&lt;br /&gt;
This will undo the last 5 migrations that have been committed to the database.&lt;br /&gt;
&lt;br /&gt;
To redo the last 5 steps, we can use a similar command&lt;br /&gt;
  $ rake db:migrate:redo STEP=5&lt;br /&gt;
&lt;br /&gt;
You can also rollback or redo a specific version of a migration state, you just need to provide the timestamp:&lt;br /&gt;
  $ rake db:migrate:up VERSION=20080906120000&lt;br /&gt;
Choose whether you want the db_migrate:up method to be executed or the db_migrate:down method&lt;br /&gt;
&lt;br /&gt;
Keep in mind, that restoring your database to a previous state will delete already inserted data completely!&lt;br /&gt;
&lt;br /&gt;
=== References ===&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66177</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66177"/>
		<updated>2012-10-03T00:20:29Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes). Some of them are listed below:&lt;br /&gt;
&lt;br /&gt;
  lock_version.&lt;br /&gt;
  &lt;br /&gt;
  type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
  &lt;br /&gt;
  id - Reserved for primary keys.&lt;br /&gt;
  &lt;br /&gt;
  table_name_count - Reserved for counter cache.&lt;br /&gt;
  &lt;br /&gt;
  position - Reserved for acts_as_list.&lt;br /&gt;
  &lt;br /&gt;
  parent_id - Reserved for acts_as_tree.&lt;br /&gt;
  &lt;br /&gt;
  lft - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
  &lt;br /&gt;
  quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
  &lt;br /&gt;
  template.&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66176</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66176"/>
		<updated>2012-10-03T00:18:38Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version.&lt;br /&gt;
&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
&lt;br /&gt;
id - Reserved for primary keys.&lt;br /&gt;
&lt;br /&gt;
table_name_count - Reserved for counter cache.&lt;br /&gt;
&lt;br /&gt;
position - Reserved for acts_as_list.&lt;br /&gt;
&lt;br /&gt;
parent_id - Reserved for acts_as_tree.&lt;br /&gt;
&lt;br /&gt;
lft - Reserved for acts_as_nested_set.&lt;br /&gt;
&lt;br /&gt;
rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
&lt;br /&gt;
template.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66175</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66175"/>
		<updated>2012-10-03T00:18:07Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version.&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
id - Reserved for primary keys.&lt;br /&gt;
table_name_count - Reserved for counter cache.&lt;br /&gt;
position - Reserved for acts_as_list.&lt;br /&gt;
parent_id - Reserved for acts_as_tree.&lt;br /&gt;
lft - Reserved for acts_as_nested_set.&lt;br /&gt;
rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
template.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66174</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66174"/>
		<updated>2012-10-03T00:17:32Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version.&lt;br /&gt;
&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
id - Reserved for primary keys.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
table_name_count - Reserved for counter cache.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
position - Reserved for acts_as_list.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
parent_id - Reserved for acts_as_tree.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
lft - Reserved for acts_as_nested_set.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
rgt - Reserved for acts_as_nested_set.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
template.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66173</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66173"/>
		<updated>2012-10-03T00:16:11Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
''ActiveRecord'' is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name&lt;br /&gt;
id - Reserved for primary keys&lt;br /&gt;
table_name_count - Reserved for counter cache&lt;br /&gt;
position - Reserved for acts_as_list&lt;br /&gt;
parent_id - Reserved for acts_as_tree&lt;br /&gt;
lft - Reserved for acts_as_nested_set&lt;br /&gt;
rgt - Reserved for acts_as_nested_set&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL&lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66172</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66172"/>
		<updated>2012-10-03T00:15:43Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The ''Active Record pattern'' is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name&lt;br /&gt;
id - Reserved for primary keys&lt;br /&gt;
table_name_count - Reserved for counter cache&lt;br /&gt;
position - Reserved for acts_as_list&lt;br /&gt;
parent_id - Reserved for acts_as_tree&lt;br /&gt;
lft - Reserved for acts_as_nested_set&lt;br /&gt;
rgt - Reserved for acts_as_nested_set&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL&lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66169</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66169"/>
		<updated>2012-10-03T00:12:24Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name&lt;br /&gt;
id - Reserved for primary keys&lt;br /&gt;
table_name_count - Reserved for counter cache&lt;br /&gt;
position - Reserved for acts_as_list&lt;br /&gt;
parent_id - Reserved for acts_as_tree&lt;br /&gt;
lft - Reserved for acts_as_nested_set&lt;br /&gt;
rgt - Reserved for acts_as_nested_set&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL&lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
   ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66168</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66168"/>
		<updated>2012-10-03T00:11:52Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version&lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name&lt;br /&gt;
id - Reserved for primary keys&lt;br /&gt;
table_name_count - Reserved for counter cache&lt;br /&gt;
position - Reserved for acts_as_list&lt;br /&gt;
parent_id - Reserved for acts_as_tree&lt;br /&gt;
lft - Reserved for acts_as_nested_set&lt;br /&gt;
rgt - Reserved for acts_as_nested_set&lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL&lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
&lt;br /&gt;
a) Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify &lt;br /&gt;
ActiveRecord::Base.use_pluralization = false. &lt;br /&gt;
&lt;br /&gt;
This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
&lt;br /&gt;
b.) Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66166</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66166"/>
		<updated>2012-10-03T00:09:55Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version &lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name &lt;br /&gt;
id - Reserved for primary keys &lt;br /&gt;
table_name_count - Reserved for counter cache &lt;br /&gt;
position - Reserved for acts_as_list &lt;br /&gt;
parent_id - Reserved for acts_as_tree &lt;br /&gt;
lft - Reserved for acts_as_nested_set &lt;br /&gt;
rgt - Reserved for acts_as_nested_set &lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL &lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify ActiveRecord::Base.use_pluralization = false. This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66165</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66165"/>
		<updated>2012-10-03T00:08:55Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: /* ACTIVE RECORD */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version &lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name &lt;br /&gt;
id - Reserved for primary keys &lt;br /&gt;
table_name_count - Reserved for counter cache &lt;br /&gt;
position - Reserved for acts_as_list &lt;br /&gt;
parent_id - Reserved for acts_as_tree &lt;br /&gt;
lft - Reserved for acts_as_nested_set &lt;br /&gt;
rgt - Reserved for acts_as_nested_set &lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL &lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
2.2 Class Naming&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify ActiveRecord::Base.use_pluralization = false. This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66164</id>
		<title>CSC/ECE 517 Fall 2012/ch1b 1w63 dv</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1b_1w63_dv&amp;diff=66164"/>
		<updated>2012-10-03T00:08:09Z</updated>

		<summary type="html">&lt;p&gt;Vrkhamke: Created page with &amp;quot; == ACTIVE RECORD ==   '''1 Introduction.'''  The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a da...&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
== ACTIVE RECORD ==&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''1 Introduction.'''&lt;br /&gt;
&lt;br /&gt;
The Active Record pattern is a Design pattern in Software Engineering which deals with the approach to store and access data in a database. The interface of an object conforming to this pattern would contain functions to perform operations like Insert,  Read, Update, and Delete. The Object will have properties that correspond to the columns in the underlying database table. This pattern is realised through ORM (Object-Relational Mapping) libraries in Programming languages.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is a module for Ruby that can be used for ORM. Thus, it is obvious that ActiveRecord will form a part of the Model in an MVC application developed in Ruby. The rest of the article discusses ActiveRecord that is the Ruby module for implementing the Active Record pattern. &lt;br /&gt;
&lt;br /&gt;
The ActiveRecord module insulates the developer from the need to use SQL in most cases. Internally, It will perform queries on the database which corresponds to the method invoked on the object. This module is compatible with most database systems (most used ones like MySQL, PostgreSQL and SQLite). Moreover, regardless of which database system the developer uses, the Active Record method format always remains the same.&lt;br /&gt;
&lt;br /&gt;
'''2 Naming'''&lt;br /&gt;
&lt;br /&gt;
	The ActiveRecord module uses a convention for naming classes, tables and fields so that the amount of configuration needed to get the functionality working is minimal. There are naming conventions on file naming, class naming, table naming etc.&lt;br /&gt;
&lt;br /&gt;
     2.1 Reserved names and Attributes:&lt;br /&gt;
    &lt;br /&gt;
Certain names are reserved and should not be used (even in the model as attributes) for example:&lt;br /&gt;
&lt;br /&gt;
lock_version &lt;br /&gt;
type - This is only used when you have single table inheritance and must contain a class name &lt;br /&gt;
id - Reserved for primary keys &lt;br /&gt;
table_name_count - Reserved for counter cache &lt;br /&gt;
position - Reserved for acts_as_list &lt;br /&gt;
parent_id - Reserved for acts_as_tree &lt;br /&gt;
lft - Reserved for acts_as_nested_set &lt;br /&gt;
rgt - Reserved for acts_as_nested_set &lt;br /&gt;
quote - Method in ActiveRecord::Base which is used to quote SQL &lt;br /&gt;
template &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
     2.2 Class Naming&lt;br /&gt;
ActiveRecord classes are named in singular form. e.g User&lt;br /&gt;
&lt;br /&gt;
     2.3 Table Naming&lt;br /&gt;
&lt;br /&gt;
Tables for ActiveRecord objects are named in plural form by default. e.g. Users&lt;br /&gt;
This naming convention can be circumvented by using below:&lt;br /&gt;
Set use_pluralization&lt;br /&gt;
In the environment.rb file we can specify ActiveRecord::Base.use_pluralization = false. This will disable pluralization for all ActiveRecord objects.&lt;br /&gt;
Use set_table_name&lt;br /&gt;
You can call set_table_name to specify a custom table name for a particular model.&lt;br /&gt;
For example:&lt;br /&gt;
  class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
    set_table_name 'user'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
3 CRUD&lt;br /&gt;
    3.1 Create&lt;br /&gt;
            &amp;lt;Use relevant code snippets&amp;gt;&lt;br /&gt;
    3.2 Read&lt;br /&gt;
   3.3 Update&lt;br /&gt;
   3.4 Delete&lt;/div&gt;</summary>
		<author><name>Vrkhamke</name></author>
	</entry>
</feed>