<?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=Mrsreena</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=Mrsreena"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Mrsreena"/>
	<updated>2026-05-13T04:41:10Z</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_2013/oss_cmh&amp;diff=80821</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80821"/>
		<updated>2013-10-30T17:03:58Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Future Work */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
The invitation controller within Expertiza handles the invite functionality which allows user to send and receives invitations. Users can create teams and invite users to join there team. The invitation controller handles the creation of the invite and the accept or decline of an invite. The invitation controller also handles requests to join teams via advertisements. After advertisements are sent a user can request to receive and invite to the team and subsequent functionality is handled by the invitation controller once an invite is sent. Our project was to refactor the code around invitations mainly dealing with the invitation controller and invitation model.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
As is noted in the project description section our project was centered around refactoring the invitation controller. Much of the functionality that was implemented within the invitation controller actually should have been in model classes. There was only about 5 lines of code in the invitation model while there were 104 lines in the invitation controller. A lot of the code in the invitation controller needed to be dispersed amongst the invitation model and various other models within the application. The code within the invitation controller was also very confusing and difficult to understand for a number of reasons. Some of the problems causing the code to be complicated included deeply nested if statements, dense methods and variable names that did not accurately reflect the values they held. The goal of our project was to make the overall design of the invitation controller simpler thus making the code easier to understand and ensuring that distribution of functionality in the application honored the MVC framework.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
Though the create method is relatively small and fairly understandable, it still asked for a few changes.There were a few method calls to the deprecated method &amp;quot;find&amp;quot; which had to be replaced with calls to the &amp;quot;first&amp;quot; and the &amp;quot;all&amp;quot; methods.&amp;lt;br&amp;gt;&lt;br /&gt;
Example:&lt;br /&gt;
The call to&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
is replaced with&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
The call to&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
is replaced with&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request user,student&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skinny Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
==== Skinny Controller, Fat Model ====&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following code served the purpose of moving a user out of their current team when they accept an invite to join another team. The code actually belonged in the teams_user model because it was affecting the teams_user table in the DB. The code was extracted into the subsequent method displayed below and called from the invitation controller.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
if old_entry != nil&lt;br /&gt;
   old_entry.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: teams-user.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The two methods displayed below are the sample method. The first iteration of refactoring produced the first version of the method. After reviewing method names and variable names we found that our first solution could be improved and this came up with the second and final version of the method. &amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def self.remove_team(user_id, team_id)&lt;br /&gt;
    team_user = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if team_user != nil&lt;br /&gt;
      team_user.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
As with the previous example we found many more examples where a few lines of code serving one purpose could be extracted into its own method. The below code serves the purpose of removing a users team from the assignment team table in the DB. This would take place if a user joins a new team and they had previously created a team and was the only member of that team.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
if old_team != nil&lt;br /&gt;
   old_team.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
This is the subsequent method call for the extracted code which was placed in the invitation controller accept method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentTeam.remove_team_by_id(params[:team_id]) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: assignment_team.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The method created in assignment_team.rb can be seen below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#Remove a team given the team id&lt;br /&gt;
def self.remove_team_by_id(id)&lt;br /&gt;
  old_team = AssignmentTeam.find(id)&lt;br /&gt;
  if old_team != nil&lt;br /&gt;
    old_team.destroy&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As in the two previous examples there were many method extractions from code within the accept method.&lt;br /&gt;
==== Code Readability ====&lt;br /&gt;
'''Scopes''' &amp;lt;br&amp;gt;&lt;br /&gt;
Scopes are a useful feature of rails that for creations of reusable constraints for database interactions. Scopes help create reusable code and more readable code. Where one would typically have to write a whole query within their code a scope and be used to minimize the need to write the same query over and over again and decrease the amount of code.&lt;br /&gt;
&lt;br /&gt;
Query within accept method:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Query within accept method with scope:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.by_team_id(params[:team_id])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Scope Added in teams_user.rb:&lt;br /&gt;
&amp;lt;pre&amp;gt;scope :by_team_id, -&amp;gt;(team_id) { where(&amp;quot;team_id = ?&amp;quot;, team_id) }&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The help promote better code readability we added a few more scopes during the course of refactoring the accept method.&lt;br /&gt;
&lt;br /&gt;
The below example shows the before and after version of a query. The subsequent version makes the query more readable. &amp;lt;br&amp;gt;&lt;br /&gt;
Before:&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id)['assignment_id']&amp;lt;/pre&amp;gt;&lt;br /&gt;
After:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id).assignment_id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Variable Names''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following variable was used to capture where a member could be added to a team (i.e. is there enough space on the team for the user to join). The boolean value was returned from a method call and stored in the following variable but we felt the variable name was not an accurate representation of it's purpose&lt;br /&gt;
&amp;lt;pre&amp;gt;add_member_return&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
so we renamed it to the following.&lt;br /&gt;
&amp;lt;pre&amp;gt;can_add_member&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After the above design changes the accept method still contained a quite a few calls to the various methods. This cause us to create a model method called accept_invite which served the purpose of encapsulating these function call into a single method that was not in the controller. This method was called from the accept method thus making the accept method considerably smaller. The purpose of the accept_invite method is to handle all of the changes that take place once a user accepts an invite. Below the starting and final version of the accept method can be seen. The accept method is much smaller and more readable since our refactoring.&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user (advertiser) a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1. Login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2. Create new course and an assignment within the course&lt;br /&gt;
    - Set all the properties appropriately&lt;br /&gt;
    - Set the assignment as a team assignment&lt;br /&gt;
    - Set the deadlines properly.&lt;br /&gt;
3. Add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4. Create a topic within the assignment&lt;br /&gt;
5. Login as user1 and select the topic in the signup sheet&lt;br /&gt;
6. Create an advertisement in the your team link of the assignments&lt;br /&gt;
7. Now login as user2 and click on signup sheet. You should see an advertisement sent out by user1.&lt;br /&gt;
8. Click on the advertise link and request an invitation.&lt;br /&gt;
9. Login as user1 again and go to the your team link.&lt;br /&gt;
10. User1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11. When user1 clicks on the invite button the request invitation should be removed and when user2 logs in again he should see the sent request as accepted.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
We working on bug fixes and refactoring we noticed that some of the error messages which were not bring displayed. The issue was that the create method was setting these error messages using notice which was not handled by the flash messages partial used throughout the application. We fixed this so that error message are now being displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:messagecmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
#The flash[:notice] is changed to flash[:note] in the invitation_controller.rb file&amp;lt;br&amp;gt;&lt;br /&gt;
#The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
===Refactoring===&lt;br /&gt;
For the current project we only focused on refactoring the invitation_controller.rb and the models associated with it.A thorough and a wholesome approach can lead to better code reuse.&amp;lt;br&amp;gt;&lt;br /&gt;
===Testing===&lt;br /&gt;
Since this project was about refactoring an existing code, we could not strictly follow the TDD model where RSpecs are written before the methods are designed.This may be considered for future assignments.&amp;lt;br&amp;gt;&lt;br /&gt;
===Documentation===&lt;br /&gt;
A detailed documentation of the invitation and the team advertisement process can be produced which will help the users understand the feature clearly.&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80802</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80802"/>
		<updated>2013-10-30T16:51:49Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Create Method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
The invitation controller within Expertiza handles the invite functionality which allows user to send and receives invitations. Users can create teams and invite users to join there team. The invitation controller handles the creation of the invite and the accept or decline of an invite. The invitation controller also handles requests to join teams via advertisements. After advertisements are sent a user can request to receive and invite to the team and subsequent functionality is handled by the invitation controller once an invite is sent. Our project was to refactor the code around invitations mainly dealing with the invitation controller and invitation model.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
As is noted in the project description section our project was centered around refactoring the invitation controller. Much of the functionality that was implemented within the invitation controller actually should have been in model classes. There was only about 5 lines of code in the invitation model while there were 104 lines in the invitation controller. A lot of the code in the invitation controller needed to be dispersed amongst the invitation model and various other models within the application. The code within the invitation controller was also very confusing and difficult to understand for a number of reasons. Some of the problems causing the code to be complicated included deeply nested if statements, dense methods and variable names that did not accurately reflect the values they held. The goal of our project was to make the overall design of the invitation controller simpler thus making the code easier to understand and ensuring that distribution of functionality in the application honored the MVC framework.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
Though the create method is relatively small and fairly understandable, it still asked for a few changes.There were a few method calls to the deprecated method &amp;quot;find&amp;quot; which had to be replaced with calls to the &amp;quot;first&amp;quot; and the &amp;quot;all&amp;quot; methods.&amp;lt;br&amp;gt;&lt;br /&gt;
Example:&lt;br /&gt;
The call to&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
is replaced with&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
The call to&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
is replaced with&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request user,student&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skinny Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
==== Skinny Controller, Fat Model ====&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following code served the purpose of moving a user out of their current team when they accept an invite to join another team. The code actually belonged in the teams_user model because it was affecting the teams_user table in the DB. The code was extracted into the subsequent method displayed below and called from the invitation controller.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
if old_entry != nil&lt;br /&gt;
   old_entry.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: teams-user.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The two methods displayed below are the sample method. The first iteration of refactoring produced the first version of the method. After reviewing method names and variable names we found that our first solution could be improved and this came up with the second and final version of the method. &amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def self.remove_team(user_id, team_id)&lt;br /&gt;
    team_user = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if team_user != nil&lt;br /&gt;
      team_user.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
As with the previous example we found many more examples where a few lines of code serving one purpose could be extracted into its own method. The below code serves the purpose of removing a users team from the assignment team table in the DB. This would take place if a user joins a new team and they had previously created a team and was the only member of that team.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
if old_team != nil&lt;br /&gt;
   old_team.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
This is the subsequent method call for the extracted code which was placed in the invitation controller accept method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentTeam.remove_team_by_id(params[:team_id]) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: assignment_team.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The method created in assignment_team.rb can be seen below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#Remove a team given the team id&lt;br /&gt;
def self.remove_team_by_id(id)&lt;br /&gt;
  old_team = AssignmentTeam.find(id)&lt;br /&gt;
  if old_team != nil&lt;br /&gt;
    old_team.destroy&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As in the two previous examples there were many method extractions from code within the accept method.&lt;br /&gt;
==== Code Readability ====&lt;br /&gt;
'''Scopes''' &amp;lt;br&amp;gt;&lt;br /&gt;
Scopes are a useful feature of rails that for creations of reusable constraints for database interactions. Scopes help create reusable code and more readable code. Where one would typically have to write a whole query within their code a scope and be used to minimize the need to write the same query over and over again and decrease the amount of code.&lt;br /&gt;
&lt;br /&gt;
Query within accept method:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Query within accept method with scope:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.by_team_id(params[:team_id])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Scope Added in teams_user.rb:&lt;br /&gt;
&amp;lt;pre&amp;gt;scope :by_team_id, -&amp;gt;(team_id) { where(&amp;quot;team_id = ?&amp;quot;, team_id) }&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The help promote better code readability we added a few more scopes during the course of refactoring the accept method.&lt;br /&gt;
&lt;br /&gt;
The below example shows the before and after version of a query. The subsequent version makes the query more readable. &amp;lt;br&amp;gt;&lt;br /&gt;
Before:&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id)['assignment_id']&amp;lt;/pre&amp;gt;&lt;br /&gt;
After:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id).assignment_id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Variable Names''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following variable was used to capture where a member could be added to a team (i.e. is there enough space on the team for the user to join). The boolean value was returned from a method call and stored in the following variable but we felt the variable name was not an accurate representation of it's purpose&lt;br /&gt;
&amp;lt;pre&amp;gt;add_member_return&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
so we renamed it to the following.&lt;br /&gt;
&amp;lt;pre&amp;gt;can_add_member&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After the above design changes the accept method still contained a quite a few calls to the various methods. This cause us to create a model method called accept_invite which served the purpose of encapsulating these function call into a single method that was not in the controller. This method was called from the accept method thus making the accept method considerably smaller. The purpose of the accept_invite method is to handle all of the changes that take place once a user accepts an invite. Below the starting and final version of the accept method can be seen. The accept method is much smaller and more readable since our refactoring.&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user (advertiser) a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1. Login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2. Create new course and an assignment within the course&lt;br /&gt;
    - Set all the properties appropriately&lt;br /&gt;
    - Set the assignment as a team assignment&lt;br /&gt;
    - Set the deadlines properly.&lt;br /&gt;
3. Add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4. Create a topic within the assignment&lt;br /&gt;
5. Login as user1 and select the topic in the signup sheet&lt;br /&gt;
6. Create an advertisement in the your team link of the assignments&lt;br /&gt;
7. Now login as user2 and click on signup sheet. You should see an advertisement sent out by user1.&lt;br /&gt;
8. Click on the advertise link and request an invitation.&lt;br /&gt;
9. Login as user1 again and go to the your team link.&lt;br /&gt;
10. User1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11. When user1 clicks on the invite button the request invitation should be removed and when user2 logs in again he should see the sent request as accepted.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
We working on bug fixes and refactoring we noticed that some of the error messages which were not bring displayed. The issue was that the create method was setting these error messages using notice which was not handled by the flash messages partial used throughout the application. We fixed this so that error message are now being displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:messagecmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
#The flash[:notice] is changed to flash[:note] in the invitation_controller.rb file&amp;lt;br&amp;gt;&lt;br /&gt;
#The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80801</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80801"/>
		<updated>2013-10-30T16:51:11Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Create Method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
The invitation controller within Expertiza handles the invite functionality which allows user to send and receives invitations. Users can create teams and invite users to join there team. The invitation controller handles the creation of the invite and the accept or decline of an invite. The invitation controller also handles requests to join teams via advertisements. After advertisements are sent a user can request to receive and invite to the team and subsequent functionality is handled by the invitation controller once an invite is sent. Our project was to refactor the code around invitations mainly dealing with the invitation controller and invitation model.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
As is noted in the project description section our project was centered around refactoring the invitation controller. Much of the functionality that was implemented within the invitation controller actually should have been in model classes. There was only about 5 lines of code in the invitation model while there were 104 lines in the invitation controller. A lot of the code in the invitation controller needed to be dispersed amongst the invitation model and various other models within the application. The code within the invitation controller was also very confusing and difficult to understand for a number of reasons. Some of the problems causing the code to be complicated included deeply nested if statements, dense methods and variable names that did not accurately reflect the values they held. The goal of our project was to make the overall design of the invitation controller simpler thus making the code easier to understand and ensuring that distribution of functionality in the application honored the MVC framework.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
Though the create method is relatively small and fairly understandable, it still asked for a few changes.There were a few method calls to the deprecated method &amp;quot;find&amp;quot; which had to be replaced with calls to the &amp;quot;first&amp;quot; and the &amp;quot;all&amp;quot; methods.&lt;br /&gt;
Example:&lt;br /&gt;
The call to&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
is replaced with&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
The call to&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
is replaced with&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request user,student&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skinny Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
==== Skinny Controller, Fat Model ====&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following code served the purpose of moving a user out of their current team when they accept an invite to join another team. The code actually belonged in the teams_user model because it was affecting the teams_user table in the DB. The code was extracted into the subsequent method displayed below and called from the invitation controller.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
if old_entry != nil&lt;br /&gt;
   old_entry.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: teams-user.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The two methods displayed below are the sample method. The first iteration of refactoring produced the first version of the method. After reviewing method names and variable names we found that our first solution could be improved and this came up with the second and final version of the method. &amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def self.remove_team(user_id, team_id)&lt;br /&gt;
    team_user = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if team_user != nil&lt;br /&gt;
      team_user.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
As with the previous example we found many more examples where a few lines of code serving one purpose could be extracted into its own method. The below code serves the purpose of removing a users team from the assignment team table in the DB. This would take place if a user joins a new team and they had previously created a team and was the only member of that team.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
if old_team != nil&lt;br /&gt;
   old_team.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
This is the subsequent method call for the extracted code which was placed in the invitation controller accept method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentTeam.remove_team_by_id(params[:team_id]) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: assignment_team.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The method created in assignment_team.rb can be seen below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#Remove a team given the team id&lt;br /&gt;
def self.remove_team_by_id(id)&lt;br /&gt;
  old_team = AssignmentTeam.find(id)&lt;br /&gt;
  if old_team != nil&lt;br /&gt;
    old_team.destroy&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As in the two previous examples there were many method extractions from code within the accept method.&lt;br /&gt;
==== Code Readability ====&lt;br /&gt;
'''Scopes''' &amp;lt;br&amp;gt;&lt;br /&gt;
Scopes are a useful feature of rails that for creations of reusable constraints for database interactions. Scopes help create reusable code and more readable code. Where one would typically have to write a whole query within their code a scope and be used to minimize the need to write the same query over and over again and decrease the amount of code.&lt;br /&gt;
&lt;br /&gt;
Query within accept method:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Query within accept method with scope:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.by_team_id(params[:team_id])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Scope Added in teams_user.rb:&lt;br /&gt;
&amp;lt;pre&amp;gt;scope :by_team_id, -&amp;gt;(team_id) { where(&amp;quot;team_id = ?&amp;quot;, team_id) }&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The help promote better code readability we added a few more scopes during the course of refactoring the accept method.&lt;br /&gt;
&lt;br /&gt;
The below example shows the before and after version of a query. The subsequent version makes the query more readable. &amp;lt;br&amp;gt;&lt;br /&gt;
Before:&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id)['assignment_id']&amp;lt;/pre&amp;gt;&lt;br /&gt;
After:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id).assignment_id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Variable Names''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following variable was used to capture where a member could be added to a team (i.e. is there enough space on the team for the user to join). The boolean value was returned from a method call and stored in the following variable but we felt the variable name was not an accurate representation of it's purpose&lt;br /&gt;
&amp;lt;pre&amp;gt;add_member_return&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
so we renamed it to the following.&lt;br /&gt;
&amp;lt;pre&amp;gt;can_add_member&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After the above design changes the accept method still contained a quite a few calls to the various methods. This cause us to create a model method called accept_invite which served the purpose of encapsulating these function call into a single method that was not in the controller. This method was called from the accept method thus making the accept method considerably smaller. The purpose of the accept_invite method is to handle all of the changes that take place once a user accepts an invite. Below the starting and final version of the accept method can be seen. The accept method is much smaller and more readable since our refactoring.&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user (advertiser) a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1. Login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2. Create new course and an assignment within the course&lt;br /&gt;
    - Set all the properties appropriately&lt;br /&gt;
    - Set the assignment as a team assignment&lt;br /&gt;
    - Set the deadlines properly.&lt;br /&gt;
3. Add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4. Create a topic within the assignment&lt;br /&gt;
5. Login as user1 and select the topic in the signup sheet&lt;br /&gt;
6. Create an advertisement in the your team link of the assignments&lt;br /&gt;
7. Now login as user2 and click on signup sheet. You should see an advertisement sent out by user1.&lt;br /&gt;
8. Click on the advertise link and request an invitation.&lt;br /&gt;
9. Login as user1 again and go to the your team link.&lt;br /&gt;
10. User1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11. When user1 clicks on the invite button the request invitation should be removed and when user2 logs in again he should see the sent request as accepted.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
We working on bug fixes and refactoring we noticed that some of the error messages which were not bring displayed. The issue was that the create method was setting these error messages using notice which was not handled by the flash messages partial used throughout the application. We fixed this so that error message are now being displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:messagecmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
#The flash[:notice] is changed to flash[:note] in the invitation_controller.rb file&amp;lt;br&amp;gt;&lt;br /&gt;
#The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80764</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80764"/>
		<updated>2013-10-30T16:28:07Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Create Method */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
The invitation controller within Expertiza handles the invite functionality which allows user to send and receives invitations. Users can create teams and invite users to join there team. The invitation controller handles the creation of the invite and the accept or decline of an invite. The invitation controller also handles requests to join teams via advertisements. After advertisements are sent a user can request to receive and invite to the team and subsequent functionality is handled by the invitation controller once an invite is sent. Our project was to refactor the code around invitations mainly dealing with the invitation controller and invitation model.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
As is noted in the project description section our project was centered around refactoring the invitation controller. Much of the functionality that was implemented within the invitation controller actually should have been in model classes. There was only about 5 lines of code in the invitation model while there were 104 lines in the invitation controller. A lot of the code in the invitation controller needed to be dispersed amongst the invitation model and various other models within the application. The code within the invitation controller was also very confusing and difficult to understand for a number of reasons. Some of the problems causing the code to be complicated included deeply nested if statements, dense methods and variable names that did not accurately reflect the values they held. The goal of our project was to make the overall design of the invitation controller simpler thus making the code easier to understand and ensuring that distribution of functionality in the application honored the MVC framework.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request user,student&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skinny Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
==== Skinny Controller, Fat Model ====&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following code served the purpose of moving a user out of their current team when they accept an invite to join another team. The code actually belonged in the teams_user model because it was affecting the teams_user table in the DB. The code was extracted into the subsequent method displayed below and called from the invitation controller.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
if old_entry != nil&lt;br /&gt;
   old_entry.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: teams-user.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The two methods displayed below are the sample method. The first iteration of refactoring produced the first version of the method. After reviewing method names and variable names we found that our first solution could be improved and this came up with the second and final version of the method. &amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def self.remove_team(user_id, team_id)&lt;br /&gt;
    team_user = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if team_user != nil&lt;br /&gt;
      team_user.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
As with the previous example we found many more examples where a few lines of code serving one purpose could be extracted into its own method. The below code serves the purpose of removing a users team from the assignment team table in the DB. This would take place if a user joins a new team and they had previously created a team and was the only member of that team.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
if old_team != nil&lt;br /&gt;
   old_team.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
This is the subsequent method call for the extracted code which was placed in the invitation controller accept method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentTeam.remove_team_by_id(params[:team_id]) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: assignment_team.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The method created in assignment_team.rb can be seen below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#Remove a team given the team id&lt;br /&gt;
def self.remove_team_by_id(id)&lt;br /&gt;
  old_team = AssignmentTeam.find(id)&lt;br /&gt;
  if old_team != nil&lt;br /&gt;
    old_team.destroy&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As in the two previous examples there were many method extractions from code within the accept method.&lt;br /&gt;
==== Code Readability ====&lt;br /&gt;
'''Scopes''' &amp;lt;br&amp;gt;&lt;br /&gt;
Scopes are a useful feature of rails that for creations of reusable constraints for database interactions. Scopes help create reusable code and more readable code. Where one would typically have to write a whole query within their code a scope and be used to minimize the need to write the same query over and over again and decrease the amount of code.&lt;br /&gt;
&lt;br /&gt;
Query within accept method:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Query within accept method with scope:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.by_team_id(params[:team_id])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Scope Added in teams_user.rb:&lt;br /&gt;
&amp;lt;pre&amp;gt;scope :by_team_id, -&amp;gt;(team_id) { where(&amp;quot;team_id = ?&amp;quot;, team_id) }&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The help promote better code readability we added a few more scopes during the course of refactoring the accept method.&lt;br /&gt;
&lt;br /&gt;
The below example shows the before and after version of a query. The subsequent version makes the query more readable. &amp;lt;br&amp;gt;&lt;br /&gt;
Before:&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id)['assignment_id']&amp;lt;/pre&amp;gt;&lt;br /&gt;
After:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;SignUpTopic.find(old_teams_signup.topic_id).assignment_id&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Variable Names''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following variable was used to capture where a member could be added to a team (i.e. is there enough space on the team for the user to join). The boolean value was returned from a method call and stored in the following variable but we felt the variable name was not an accurate representation of it's purpose&lt;br /&gt;
&amp;lt;pre&amp;gt;add_member_return&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
so we renamed it to the following.&lt;br /&gt;
&amp;lt;pre&amp;gt;can_add_member&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
After the above design changes the accept method still contained a quite a few calls to the various methods. This cause us to create a model method called accept_invite which served the purpose of encapsulating these function call into a single method that was not in the controller. This method was called from the accept method thus making the accept method considerably smaller. The purpose of the accept_invite method is to handle all of the changes that take place once a user accepts an invite. Below the starting and final version of the accept method can be seen. The accept method is much smaller and more readable since our refactoring.&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user (advertiser) a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1. Login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2. Create new course and an assignment within the course&lt;br /&gt;
    - Set all the properties appropriately&lt;br /&gt;
    - Set the assignment as a team assignment&lt;br /&gt;
    - Set the deadlines properly.&lt;br /&gt;
3. Add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4. Create a topic within the assignment&lt;br /&gt;
5. Login as user1 and select the topic in the signup sheet&lt;br /&gt;
6. Create an advertisement in the your team link of the assignments&lt;br /&gt;
7. Now login as user2 and click on signup sheet. You should see an advertisement sent out by user1.&lt;br /&gt;
8. Click on the advertise link and request an invitation.&lt;br /&gt;
9. Login as user1 again and go to the your team link.&lt;br /&gt;
10. User1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11. When user1 clicks on the invite button the request invitation should be removed and when user2 logs in again he should see the sent request as accepted.&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
We working on bug fixes and refactoring we noticed that some of the error messages which were not bring displayed. The issue was that the create method was setting these error messages using notice which was not handled by the flash messages partial used throughout the application. We fixed this so that error message are now being displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:messagecmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
#The flash[:notice] is changed to flash[:note] in the invitation_controller.rb file&amp;lt;br&amp;gt;&lt;br /&gt;
#The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80464</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80464"/>
		<updated>2013-10-29T23:18:19Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Problem Description */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skinny Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
==== Skinny Controller, Fat Model ====&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
The following code served the purpose of moving a user out of their current team when they accept an invite to join another team. The code actually belonged in the teams_user model because it was affecting the teams_user table in the DB. The code was extracted into the subsequent method displayed below and called from the invitation controller.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
if old_entry != nil&lt;br /&gt;
   old_entry.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: teams-user.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The two methods displayed below are the sample method. The first iteration of refactoring produced the first version of the method. After reviewing method names and variable names we found that our first solution could be improved and this came up with the second and final version of the method. &amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
def self.remove_team(user_id, team_id)&lt;br /&gt;
    team_user = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if team_user != nil&lt;br /&gt;
      team_user.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''Before: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
As with the previous example we found many more examples where a few lines of code serving one purpose could be extracted into its own method. The below code serves the purpose of removing a users team from the assignment team table in the DB. This would take place if a user joins a new team and they had previously created a team and was the only member of that team.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
if old_team != nil&lt;br /&gt;
   old_team.destroy&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: invitation_controller.rb - accept method''' &amp;lt;br&amp;gt;&lt;br /&gt;
This is the subsequent method call for the extracted code which was placed in the invitation controller accept method.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
AssignmentTeam.remove_team_by_id(params[:team_id]) &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After: assignment_team.rb''' &amp;lt;br&amp;gt;&lt;br /&gt;
The method created in assignment_team.rb can be seen below.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
#Remove a team given the team id&lt;br /&gt;
def self.remove_team_by_id(id)&lt;br /&gt;
  old_team = AssignmentTeam.find(id)&lt;br /&gt;
  if old_team != nil&lt;br /&gt;
    old_team.destroy&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As in the two previous examples there were many method extractions from code within the accept method.&lt;br /&gt;
==== Code Readability ====&lt;br /&gt;
'''Scopes''' &amp;lt;br&amp;gt;&lt;br /&gt;
Scopes are a useful feature of rails that for creations of reusable constraints for database interactions. Scopes help create reusable code and more readable code. Where one would typically have to write a whole query within their code a scope and be used to minimize the need to write the same query over and over again and decrease the amount of code.&lt;br /&gt;
&lt;br /&gt;
Query within accept method:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Query within accept method with scope:&lt;br /&gt;
&amp;lt;pre&amp;gt;other_members = TeamsUser.by_team_id(params[:team_id])&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Scope Added in teams_user.rb:&lt;br /&gt;
&amp;lt;pre&amp;gt;scope :by_team_id, -&amp;gt;(team_id) { where(&amp;quot;team_id = ?&amp;quot;, team_id) }&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The help promote better code readability we added a few more scopes during the course of refactoring the accept method.&lt;br /&gt;
&lt;br /&gt;
Below the starting and final version of the accept method can be seen. The accept method is much smaller and more readable since our refactoring.&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
Some of the error messages which were not getting displayed are now getting displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
[[File:messagecmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
1)The flash[:notice] is changes to flash[:note] in the invitation_controller.rb file&amp;lt;br&amp;gt;&lt;br /&gt;
2)The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80447</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80447"/>
		<updated>2013-10-29T22:08:19Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Code Changes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
Some of the error messages which were not getting displayed are now getting displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
1)The flash[:notice] is changes to flash[:note] in the invitation_controller.rb file&amp;lt;br&amp;gt;&lt;br /&gt;
2)The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80446</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80446"/>
		<updated>2013-10-29T22:07:58Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Error Messages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
====Problem Description====&lt;br /&gt;
Some of the error messages which were not getting displayed are now getting displayed properly as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Code Changes====&lt;br /&gt;
1)The flash[:notice] is changes to flash[:note] in the invitation_controller.rb file&lt;br /&gt;
2)The _flash_messages.html.erb file is updated to include :notice which may be used in some other parts of the application.&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80445</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80445"/>
		<updated>2013-10-29T21:59:13Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Code changes done to fix the bug */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
.The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80444</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80444"/>
		<updated>2013-10-29T21:58:49Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Bug Fixes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
====Code changes done to fix the bug====&lt;br /&gt;
A new method was introduced to update the &amp;quot;status&amp;quot; field of the join_table_requests&lt;br /&gt;
The method is a follows:&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def update_join_team_request&lt;br /&gt;
    old_entry = JoinTeamRequest.first(:conditions =&amp;gt; ['participant_id =? and team_id =?', params[:participant_id],params[:team_id]])&lt;br /&gt;
    if old_entry&lt;br /&gt;
       old_entry.update_attribute(&amp;quot;status&amp;quot;,'A')&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt; &lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80443</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80443"/>
		<updated>2013-10-29T21:54:58Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Problem Description */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80442</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80442"/>
		<updated>2013-10-29T21:54:44Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Problem Description */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&amp;lt;/br&amp;gt;&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&amp;lt;/br&amp;gt;&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80441</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80441"/>
		<updated>2013-10-29T21:53:53Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Problem Description */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
====Complete steps to reproduce the bug fix====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80440</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80440"/>
		<updated>2013-10-29T21:53:14Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Complete steps to reproduce the bug fix:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80439</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80439"/>
		<updated>2013-10-29T21:52:53Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Invite Requests */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
[[File:Receivercmh.jpg]]&lt;br /&gt;
[[File:sendcmh.jpg]]&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
The theme that we went with for refactoring the accept method is “Skin Controller, Fat Model.” &amp;lt;ref&amp;gt; Best Practices [http://www.sitepoint.com/10-ruby-on-rails-best-practices/ &amp;quot;10 Ruby on Rails Best Practices&amp;quot;]  &amp;lt;/ref&amp;gt; We wanted to move much of the logistics out of the accept method letting models handle this while keeping the controller limited to being the interface between the view and model. Before accept method was refactored it was very dense and contained too much functionality. The accept method was in the invitation controller was performing much of the invitation logic that should have been handled in the invitation model and various other models throughout the application. The accept method also played many different roles in that not only was it handling items that the model was responsible for but it was performing many different operations. There are many actions that need to take place when a user accepts an invitation and the controller method was taking care of all of these things. We began to eliminate these issues by extracting smaller operations that the accept method was handling into various methods and moving this code into various models such as the invitation.rb, signed_up_user.rb and team_user.rb.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
TeamsUser.remove_previous_team(student.user_id, params[:team_id])&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
'''teams_user.rb'''&lt;br /&gt;
&lt;br /&gt;
def self.remove_previous_team(user_id, team_id)&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', user_id, team_id])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The accept method within the controller had too much functionality. We first moved much of the functionality within the accept method to a model accept method which purpose is to make sure that all items that need to be taken care of upon a method accept are in fact handled. Just moving this code to the model did not solve the issue of complexity. We created smaller methods to handle individual changes that needed to be taken care of for example upon an accept the users topic must be updated, the topics they are waitlisted for must be dropped, amongst many other things. We took these smaller changes that needed to be made and moved them into separate methods amongst various models like signed_up_user.rb and teams_user.rb. We also noticed that some variable names did not do a good job of describing their focus so we changed these variable names to increase readability. After our refactoring the accept method is much smaller and much more readable.&amp;lt;ref&amp;gt; Coding Conventions [http://www.slideshare.net/davidpaluy/ruby-on-rails-coding-conventions-standards-and-best-practices &amp;quot;Ruby On Rails coding conventions, standards and best practices&amp;quot;]  &amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
==== Problem Description ====&lt;br /&gt;
&lt;br /&gt;
When a particular user responds to a advertisement sent out by another user(advertiser), a new Request invitation is created which is displayed in the advertiser's received request section of the team page as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
When the advertiser clicks on the invite, the corresponding received request should be removed from the received requests list and the request sender should see the status as accepted when he logs in again as shown below:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Complete steps to reproduce the bug fix:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1)login as admin with password&amp;quot;pass&amp;quot;&lt;br /&gt;
&lt;br /&gt;
2) create new course and an assignment within the course&lt;br /&gt;
    set all the properties appropriately-&lt;br /&gt;
    set the assignment as a team assignment &lt;br /&gt;
    set the deadlines properly.&lt;br /&gt;
3) add 2 participants(user1 and user2) to the assignment(users need to be created who act as participants)&lt;br /&gt;
4) create a topic within the assignment&lt;br /&gt;
5) login as user1 and select the topic in the signup sheet&lt;br /&gt;
6) create an advertisement in the your team link of the assignments&lt;br /&gt;
7) Now login as user2 and click on signupsheet.You should see an advertisement sent out by user1.&lt;br /&gt;
8) click on the advertise link and request an invitation.&lt;br /&gt;
9) Login as user1 again and go to the your team link.&lt;br /&gt;
10) user1 should see the the invitation request in the received requests with the invite and decline button next to it.&lt;br /&gt;
11)when user1 clicks on the invite button, the request invitation should be removed and when user2 logs in again , he should see the sent request as accepted&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Receivercmh.jpg&amp;diff=80425</id>
		<title>File:Receivercmh.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Receivercmh.jpg&amp;diff=80425"/>
		<updated>2013-10-29T21:36:40Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: uploaded a new version of &amp;amp;quot;File:Receivercmh.jpg&amp;amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Receivercmh.jpg&amp;diff=80424</id>
		<title>File:Receivercmh.jpg</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Receivercmh.jpg&amp;diff=80424"/>
		<updated>2013-10-29T21:35:54Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Receivercmh.png&amp;diff=80422</id>
		<title>File:Receivercmh.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Receivercmh.png&amp;diff=80422"/>
		<updated>2013-10-29T21:34:03Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80410</id>
		<title>CSC/ECE 517 Fall 2013/oss cmh</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/oss_cmh&amp;diff=80410"/>
		<updated>2013-10-29T21:21:46Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;== Introduction ==&lt;br /&gt;
&lt;br /&gt;
What the invitation controller does and the process advertising, creating invites and accepting invites.&lt;br /&gt;
&lt;br /&gt;
== Project Description ==&lt;br /&gt;
'''Classes:''' invitation_controller.rb (104 lines)&lt;br /&gt;
	invitation.rb (5 lines)&lt;br /&gt;
&lt;br /&gt;
'''What it does:''' Handles invitations to join teams.&lt;br /&gt;
&lt;br /&gt;
'''What needs to be done:'''  The code is deeply nested and quite confusing.  There should be a single method responsible for finding whether a user is already on a team, adding someone onto a waitlist, dropping someone off of a waitlist, changing/updating the topic that the user is assigned to, etc.  Some of these methods should be in model classes, such as invitation.rb and signed_up_user.rb.  Break the complicated methods into shorter methods with clear names, and place these methods in the most appropriate class, moving a lot of functionality to the model classes.&lt;br /&gt;
&lt;br /&gt;
Currently, after someone joins a team, pending invitations are not removed.  There should be a method handling deletion of invitations (including declined invitations) to a user after that user joins a team.  This should be a model method.&lt;br /&gt;
&lt;br /&gt;
Though this class is not long, the code looks and reads like it is very complicated.  Breaking it down into multiple methods with clear names and proper division of functionality between classes will be a challenge.&lt;br /&gt;
&lt;br /&gt;
== Motivation ==&lt;br /&gt;
&lt;br /&gt;
Briefly talk about why invitation controller needed refactoring.&lt;br /&gt;
&lt;br /&gt;
== Design Changes ==&lt;br /&gt;
&lt;br /&gt;
=== Create Method ===&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create    &lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant = AssignmentParticipant.find(:first, :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:notice] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:notice] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          sent_invitation = Invitation.find(:all, :conditions =&amp;gt; ['from_id = ? and to_id = ? and assignment_id = ? and reply_status = &amp;quot;W&amp;quot;', student.user_id, user.id, student.parent_id])&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if sent_invitation.length == 0&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:notice] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def create&lt;br /&gt;
    user = User.find_by_name(params[:user][:name].strip)&lt;br /&gt;
    team = AssignmentTeam.find_by_id(params[:team_id])&lt;br /&gt;
    student = AssignmentParticipant.find(params[:student_id])&lt;br /&gt;
    return unless current_user_id?(student.user_id)&lt;br /&gt;
&lt;br /&gt;
    #check if the invited user is valid&lt;br /&gt;
    if !user&lt;br /&gt;
      flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; does not exist. Please make sure the name entered is correct.&amp;quot;&lt;br /&gt;
    else&lt;br /&gt;
      participant= AssignmentParticipant.first( :conditions =&amp;gt; ['user_id =? and parent_id =?', user.id, student.parent_id])&lt;br /&gt;
      #check if the user is a participant of the assignment&lt;br /&gt;
      if !participant&lt;br /&gt;
        flash[:note] = &amp;quot;\&amp;quot;#{params[:user][:name].strip}\&amp;quot; is not a participant of this assignment.&amp;quot;&lt;br /&gt;
      else&lt;br /&gt;
        team_member = TeamsUser.all(:conditions =&amp;gt; ['team_id =? and user_id =?', team.id, user.id])&lt;br /&gt;
        #check if invited user is already in the team&lt;br /&gt;
        if (team_member.size &amp;gt; 0)&lt;br /&gt;
          flash[:note] = &amp;quot;\&amp;quot;#{user.name}\&amp;quot; is already a member of team.&amp;quot;&lt;br /&gt;
        else&lt;br /&gt;
          #check if the invited user is already invited (i.e. awaiting reply)&lt;br /&gt;
          if Invitation.is_invited?(student.user_id, user.id, student.parent_id)&lt;br /&gt;
            @invitation = Invitation.new&lt;br /&gt;
            @invitation.to_id = user.id&lt;br /&gt;
            @invitation.from_id = student.user_id&lt;br /&gt;
            @invitation.assignment_id = student.parent_id&lt;br /&gt;
            @invitation.reply_status = 'W'&lt;br /&gt;
            @invitation.save&lt;br /&gt;
          else&lt;br /&gt;
            flash[:note] = &amp;quot;You have already sent an invitation to \&amp;quot;#{user.name}\&amp;quot;.&amp;quot;&lt;br /&gt;
          end&lt;br /&gt;
        end&lt;br /&gt;
      end&lt;br /&gt;
    end&lt;br /&gt;
&lt;br /&gt;
    update_join_team_request&lt;br /&gt;
&lt;br /&gt;
    redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id=&amp;gt; student.id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Accept Method ===&lt;br /&gt;
&lt;br /&gt;
'''Before Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
    @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
    @inv.reply_status = 'A'&lt;br /&gt;
    @inv.save&lt;br /&gt;
    &lt;br /&gt;
    student = Participant.find(params[:student_id])&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation, remove your previous entry in the teams_users table.&lt;br /&gt;
    old_entry = TeamsUser.find(:first, :conditions =&amp;gt; ['user_id = ? and team_id = ?', student.user_id, params[:team_id]])&lt;br /&gt;
    if old_entry != nil&lt;br /&gt;
      old_entry.destroy&lt;br /&gt;
    end&lt;br /&gt;
    &lt;br /&gt;
    #if you are on a team and you accept another invitation and if your old team does not have any members, delete the entry for the team&lt;br /&gt;
    other_members = TeamsUser.find(:all, :conditions =&amp;gt; ['team_id = ?', params[:team_id]])&lt;br /&gt;
    if other_members.nil? || other_members.length == 0&lt;br /&gt;
      old_team = AssignmentTeam.find(:first, :conditions =&amp;gt; ['id = ?', params[:team_id]])&lt;br /&gt;
      if old_team != nil&lt;br /&gt;
        old_team.destroy&lt;br /&gt;
      end&lt;br /&gt;
&lt;br /&gt;
      #if a signup sheet exists then release all the topics selected by this team into the pool.&lt;br /&gt;
      old_teams_signups = SignedUpUser.find_all_by_creator_id(params[:team_id])&lt;br /&gt;
      if !old_teams_signups.nil?&lt;br /&gt;
        for old_teams_signup in old_teams_signups&lt;br /&gt;
          if old_teams_signup.is_waitlisted == false # i.e., if the old team was occupying a slot, &amp;amp; thus is releasing a slot ...&lt;br /&gt;
            first_waitlisted_signup = SignedUpUser.find_by_topic_id_and_is_waitlisted(old_teams_signup.topic_id, true)&lt;br /&gt;
            if !first_waitlisted_signup.nil?&lt;br /&gt;
              #As this user is going to be allocated a confirmed topic, all of his waitlisted topic signups should be purged&lt;br /&gt;
              first_waitlisted_signup.is_waitlisted = false&lt;br /&gt;
              first_waitlisted_signup.save&lt;br /&gt;
&lt;br /&gt;
              #Also update the participant table. But first_waitlisted_signup.creator_id is the team id&lt;br /&gt;
              #so find one of the users on the team because the update_topic_id function in participant&lt;br /&gt;
              #will take care of updating all the participants on the team&lt;br /&gt;
              user_id = TeamsUser.find(:first, :conditions =&amp;gt; {:team_id =&amp;gt; first_waitlisted_signup.creator_id}).user_id&lt;br /&gt;
              participant = Participant.find_by_user_id_and_parent_id(user_id,old_team.assignment.id)&lt;br /&gt;
              participant.update_topic_id(old_teams_signup.topic_id)&lt;br /&gt;
               &lt;br /&gt;
              SignUpTopic.cancel_all_waitlists(first_waitlisted_signup.creator_id, SignUpTopic.find(old_teams_signup.topic_id)['assignment_id'])&lt;br /&gt;
            end # if !first_waitlisted_signup.nil&lt;br /&gt;
            # Remove the now-empty team from the slot it is occupying.&lt;br /&gt;
          end # if old_teams_signup.is_waitlisted == false&lt;br /&gt;
          old_teams_signup.destroy&lt;br /&gt;
        end&lt;br /&gt;
    end&lt;br /&gt;
 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
'''After Refactor'''&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
def accept&lt;br /&gt;
  @inv = Invitation.find(params[:inv_id])&lt;br /&gt;
  @inv.reply_status = 'A'&lt;br /&gt;
  @inv.save&lt;br /&gt;
&lt;br /&gt;
  invited_user_id = Participant.find(params[:student_id]).user_id&lt;br /&gt;
    &lt;br /&gt;
  #Remove the users previous team since they are accepting an invite for possibly a new team.&lt;br /&gt;
  TeamsUser.remove_team(invited_user_id, params[:team_id])&lt;br /&gt;
  #Accept the invite and return boolean on whether the add was successful&lt;br /&gt;
  add_successful = Invitation.accept_invite(params[:team_id], @inv.from_id, @inv.to_id)&lt;br /&gt;
  #If add wasn't successful because team was full display message&lt;br /&gt;
  unless add_successful&lt;br /&gt;
    flash[:error]= &amp;quot;The team already has the maximum number of members.&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  redirect_to :controller =&amp;gt; 'student_team', :action =&amp;gt; 'view', :id =&amp;gt; Participant.find(params[:student_id]).id&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== Bug Fixes ==&lt;br /&gt;
&lt;br /&gt;
=== Invite Requests ===&lt;br /&gt;
&lt;br /&gt;
=== Error Messages ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Future Work ==&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79845</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79845"/>
		<updated>2013-10-07T20:51:26Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Squeel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
[http://datamapper.org/why.html  DataMapper] is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular web-services.&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries.&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields.&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation).&lt;br /&gt;
*An API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,Apache Solr and web services such as Salesforce.&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
[http://rubydoc.info/gems/squeel/1.1.1/frames Squeel] unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79844</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79844"/>
		<updated>2013-10-07T20:51:02Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
[http://datamapper.org/why.html  DataMapper] is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular web-services.&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries.&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields.&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation).&lt;br /&gt;
*An API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,Apache Solr and web services such as Salesforce.&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
[https://www.ruby-toolbox.com/categories/orm Squeel] unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79843</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79843"/>
		<updated>2013-10-07T20:49:28Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Active Record */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
[http://datamapper.org/why.html  DataMapper] is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular web-services.&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries.&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields.&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation).&lt;br /&gt;
*An API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,Apache Solr and web services such as Salesforce.&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
[https://www.ruby-toolbox.com/categories/orm Squeel] unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79842</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79842"/>
		<updated>2013-10-07T20:48:27Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* DataMapper */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
[http://datamapper.org/why.html  DataMapper] is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular web-services.&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries.&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields.&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation).&lt;br /&gt;
*An API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern. As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,Apache Solr and web services such as Salesforce.&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
[https://www.ruby-toolbox.com/categories/orm Squeel] unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79839</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79839"/>
		<updated>2013-10-07T20:45:03Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* NonSQL databases */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
[https://www.ruby-toolbox.com/categories/orm Squeel] unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NonSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79838</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79838"/>
		<updated>2013-10-07T20:43:53Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Squeel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
[https://www.ruby-toolbox.com/categories/orm Squeel] unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79837</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79837"/>
		<updated>2013-10-07T20:43:28Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79836</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79836"/>
		<updated>2013-10-07T20:42:48Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* MyBatis/iBatis */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
[http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis] was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [https://www.ruby-toolbox.com/categories/orm Squeel]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79835</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79835"/>
		<updated>2013-10-07T20:42:20Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [https://www.ruby-toolbox.com/categories/orm Squeel]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79834</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79834"/>
		<updated>2013-10-07T20:41:53Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to ActiveRecord. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use '''where''' clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/ MyBatis/iBatis]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/MyBatis MyBatis/iBatis]&lt;br /&gt;
# [https://www.ruby-toolbox.com/categories/orm Squeel]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames Squeel]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79831</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79831"/>
		<updated>2013-10-07T20:40:49Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0. Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;br /&gt;
# [http://loianegroner.com/2011/02/introduction-to-ibatis-mybatis-an-alternative-to-hibernate-and-jdbc/]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/MyBatis]&lt;br /&gt;
# [https://www.ruby-toolbox.com/categories/orm]&lt;br /&gt;
# [http://rubydoc.info/gems/squeel/1.1.1/frames]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79829</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79829"/>
		<updated>2013-10-07T20:39:04Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Disadvantages of ORM */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you are using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.&lt;br /&gt;
&lt;br /&gt;
'''Pros'''–&lt;br /&gt;
* Integrated with popular Rails development framework.&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent.&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes.&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
'''Features''' -&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
'''Features'''-&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**Queries can’t be optimized.&lt;br /&gt;
**Queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**Compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**Database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79824</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79824"/>
		<updated>2013-10-07T20:32:00Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Disadvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79823</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79823"/>
		<updated>2013-10-07T20:31:46Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Advantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages of ORM=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79822</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79822"/>
		<updated>2013-10-07T20:31:19Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* NonSQL databases: */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79820</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79820"/>
		<updated>2013-10-07T20:30:37Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases:=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping  Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm  The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping  Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79819</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79819"/>
		<updated>2013-10-07T20:30:10Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases:=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping , Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm , The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping , Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79818</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79818"/>
		<updated>2013-10-07T20:29:40Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Disadvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases:=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping , Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance&lt;br /&gt;
Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm , The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping , Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79817</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79817"/>
		<updated>2013-10-07T20:26:33Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Advantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases:=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
&lt;br /&gt;
*ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
[http://www.codefutures.com/weblog/andygrove/archives/2005/02/data_access_obj.html][wikipedia]&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping , Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance&lt;br /&gt;
Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm , The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping , Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79816</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79816"/>
		<updated>2013-10-07T20:25:20Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* NonSQL databases: */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects, Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributes retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
When applied to Ruby, implementations of ORM often leverage the language’s Meta-programming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used. With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needs to be extracted from the model and the database, and be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases:=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. &lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://blogs.msdn.com/b/gblock/archive/2006/10/26/ten-advantages-of-an-orm.aspx]&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
[http://www.codefutures.com/weblog/andygrove/archives/2005/02/data_access_obj.html][wikipedia]&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping , Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance&lt;br /&gt;
Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm , The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping , Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79814</id>
		<title>CSC/ECE 517 Fall 2013/ch1 1w43 sm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2013/ch1_1w43_sm&amp;diff=79814"/>
		<updated>2013-10-07T20:22:43Z</updated>

		<summary type="html">&lt;p&gt;Mrsreena: /* Squeel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;=Object Relational Mapping=&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
=Introduction=&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_mapping Object-relational mapping (ORM)], or ORM, is a programming technique which associates data stored in a relational database with application objects. The ORM layer populates business objects on demand and persists them back into the relational database when updated.&lt;br /&gt;
ORM basically creates a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools.In this wiki, we concenterate mainly on the top Ruby ORM's like Active Record,Sequel and DataMapper.Also, it includes a comparison of various ORM techniques  and the advantages and disadvantages of various styles of ORM mapping.&lt;br /&gt;
&lt;br /&gt;
=Need For ORM=&lt;br /&gt;
Need for ORM arose due to a major problem called the Object-Relational Impedance MisMatch Problem.&lt;br /&gt;
[http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance MisMatch Problem] is a set of conceptual and technical difficulties, encountered when a relational database management system (RDBMS) is being used by an object-oriented program particularly when object/class definitions are mapped directly to database tables or schema.It implies that object models don't work together with relational models, i.e RDBMS represents data in tabular format while Object oriented languages represent data in the form of interconnected graph of objects.&lt;br /&gt;
The Mismatches that occur in Object-Oriented concepts are as follows: &lt;br /&gt;
*Encapsulation:&lt;br /&gt;
Mapping of private object representation to database tables is difficult due to availability of fewer constraints for the design of private representation as opposed to public data in RDBMS.&lt;br /&gt;
*Interface, Class, Inheritance and polymorphism:&lt;br /&gt;
Under an object-oriented paradigm, objects have interfaces that together provide the only access to the internals of that object. The relational model, on the other hand, utilizes derived relation variables (views) to provide varying perspectives and constraints to ensure integrity. Similarly, essential OOP concepts for classes of objects, inheritance and polymorphism are not supported by relational database systems.&lt;br /&gt;
*Identity:&lt;br /&gt;
RDBMS defines exactly one notion of 'sameness': the primary key. However, Object-oriented languages, for example Java, defines both object identity (a==b) and object equality (a.equals(b)).&lt;br /&gt;
*Associations:&lt;br /&gt;
Associations are represented as unidirectional references in Object Oriented languages whereas RDBMS uses the notion of foreign keys. For example, If you need bidirectional relationships in Java, you must define the association twice.Likewise, you cannot determine the multiplicity of a relationship by looking at the object domain model.&lt;br /&gt;
*Data navigation:&lt;br /&gt;
The way you access data in object-oriented languages is fundamentally different than the way you do it in a relational database. Like in Java, you navigate from one association to another walking the object network. This is not an efficient way of retrieving data from a relational database. You typically want to minimize the number of SQL queries and thus load several entities via JOINs and select the targeted entities before you start walking the object network.&lt;br /&gt;
&lt;br /&gt;
=Overview=&lt;br /&gt;
&lt;br /&gt;
Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects that are almost always non-scalar values. Like for example, Consider a Geometric object, an entity which can have shape and color.In the object oriented implementation, this entity would be modeled as a geometric object with shape and color as its attributes.Shape itself can contain objects like for triangles(equilateral or isosceles) and so on.Here each geometric object can be treated as a single object by any programming language and its attributes can be also accessed by various object methods.However, many popular database products such as structured query language database management systems (SQL DBMS) can only store and manipulate scalar values such as integers and strings organized within tables.&lt;br /&gt;
&lt;br /&gt;
Hence, the programmer must either convert the object values into groups of simpler values for storage in the database (and convert them back upon retrieval), or only use simple scalar values within the program. Object-relational mapping is used to implement the first approach.The key is to translate the logical representation of the objects into an atomized form that is capable of being stored in the database, while somehow preserving the properties of the objects and their relationships so that they can be reloaded as an object whenever required. If this storage and retrieval functionality is implemented, the objects are then said to be persistent.&lt;br /&gt;
&lt;br /&gt;
Object-Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system. Using ORM, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing SQL statements directly and with less overall database access code.&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
Typical ORM features:&lt;br /&gt;
* Automatic mapping from classes to database tables&lt;br /&gt;
** Class instance variables to database columns&lt;br /&gt;
** Class instances to table rows&lt;br /&gt;
* Aggregation and association relationships between mapped classes are managed&lt;br /&gt;
** Example, :has_many, :belongs_to associations in ActiveRecord&lt;br /&gt;
** Inheritance cases are mapped to tables&lt;br /&gt;
* Validation of data prior to table storage&lt;br /&gt;
* Class extensions to enable search, as well as creation, read, update, and deletion (CRUD) of instances/records&lt;br /&gt;
* Usually abstracts the database from program space in such a way that alternate database types can be easily chosen (SQLite, Oracle, etc)&lt;br /&gt;
&lt;br /&gt;
The diagram below depicts a simple mapping of an object to a database table&lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic1.jpg]]&lt;br /&gt;
&lt;br /&gt;
ORM makes access to database through the application extremely easy, as it provides connection from model of the program to the database.Treating database rows as objects,Program can easily access the information in more consistent manner.Also it gives flexibility to the programmers to manipulate the data with the language itself rather than working on the attributed retrieved from the database.&lt;br /&gt;
&lt;br /&gt;
[When applied to Ruby, implementations of ORM often leverage the language’s metaprogramming strengths to create intuitive application-specific methods and otherwise extend classes to support database functionality. With the addition of Rails, the ORM becomes much more important, as it is necessary to have an ORM to connect the models of the MVC (model-view-controller) stack used by Ruby on Rails with the application's database. Since the models are Ruby objects, the ORM allows modifications to the database to be done through changes to these models, independent of the type of database used.&lt;br /&gt;
With the release of Rails 3.0, the platform became ORM independent. With this change, it is much easier to use the ORM most preferred by the programmer, rather than being corralled into using one particular one. To allow this, the ORM needed to be extracted from the model and the database, to be a pure mediator between the two. Then any ORM can be used as long as it can successfully understand the model and the database used.]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Active Record=&lt;br /&gt;
[http://ar.rubyonrails.org/ ActiveRecord] insulates you from the need to use raw SQL to find database records.Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.[edgeguides]&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default ‘model’ component of the model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.[2]&lt;br /&gt;
&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. For example, DataMapper and Sequel show major improvements over the original ActiveRecord framework.[neutrality is disputed] As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 is independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.[wiki]&lt;br /&gt;
&lt;br /&gt;
To create a table, ActiveRecord makes use of a migration class rather than including table definition in the actual class being modeled.  As an example, the following code creates a table ‘’users’’ to store a collection of class ‘’User’’ objects:&lt;br /&gt;
&amp;lt;pre&amp;gt;&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.string :email&lt;br /&gt;
      t.string :age&lt;br /&gt;
	  t.references :cheer&lt;br /&gt;
	  t.references :post&lt;br /&gt;
&lt;br /&gt;
      t.timestamps     # add creation and modification timestamps&lt;br /&gt;
    end&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
  def self.down        # undo the table creation&lt;br /&gt;
    drop_table :users&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note in the preceding example, that the ActiveRecord’s migration scheme provides a means for backing out changes via the ‘’self.down’’ method.  In addition, a table key ‘’id’’ is added to the new table without an explicit definition and record creation and modification timestamps are included via the ‘’timestamps’’ method provided by ActiveRecord.  &lt;br /&gt;
&lt;br /&gt;
ActiveRecord manages associations between table elements and provides the means to define such associations in the model definition.  For example, the ‘’User’’ class shown below defines a ‘’has_many’’ (one-to-many) association with both the cheers and posts tables. These associations are represented in the migration class with the references operator.  Also note ActiveRecord’s integrated support for validation of table information when attempting an update.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; ActiveRecord::Base&lt;br /&gt;
  has_many :cheers&lt;br /&gt;
  has_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence_of :name&lt;br /&gt;
  validates_presence_of :age&lt;br /&gt;
  validates_uniqueness_of :name&lt;br /&gt;
  validates_length_of :name, :within =&amp;gt; 3..20&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in the table one calls the class function related to that column. For example, to find the user whose name is Bob, one would use @user = User.find_by_name('Bob'). Then one could find Bob's e-mail by using @user.email. Users can be searched for by any attribute in this way, as find methods are created for every combination of attributes.&lt;br /&gt;
While ActiveRecord provides the flexibility to create more sophisticated table relationships to represent class hierarchy, its base scheme is a single table inheritance, which trades some storage efficiency for simplicity in the database design. The following figure illustrates this concept of simplicity over efficiency.  &lt;br /&gt;
&lt;br /&gt;
[[Image:3j_ks_pic2.jpg]]&lt;br /&gt;
&lt;br /&gt;
Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the ActiveRecord method format will always be the same.&lt;br /&gt;
To retrieve objects from the database, Active Record provides several finder methods. Each finder method allows you to pass arguments into it to perform certain queries on your database without writing raw SQL.[guide.rubyonrails]&lt;br /&gt;
&lt;br /&gt;
'''Pros''' –&lt;br /&gt;
* Integrated with popular Rails development framework&lt;br /&gt;
*Dynamically created database search methods (eg: User.find_by_address) ease db queries and make queries database syntax independent&lt;br /&gt;
*DB creation/management using the migrate scheme provides a means for backing out unwanted table changes&lt;br /&gt;
'''Cons''' –&lt;br /&gt;
*DB creation/management is decoupled from the model, requiring a separate utility (rake/migrate) that must be kept in sync with application.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Sequel=&lt;br /&gt;
[http://sequel.rubyforge.org Sequel] is designed to take the hassle away from connecting to databases and manipulating them. Sequel deals with all the boring stuff like maintaining connections, formatting SQL correctly and fetching records so you can concentrate on your application.&lt;br /&gt;
Sequel uses the concept of datasets to retrieve data. A Dataset object encapsulates an SQL query and supports chainability, letting you fetch data using a convenient Ruby DSL that is both concise and flexible.The current sequel version is 4.2.0.Initially Sequel had three core modules - sequel, sequel_core and sequel_model. Starting from version 1.4 , sequel and sequel_model were merged. Sequel handles validations using a validation plug-in and helpers.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is an object relational mapper built on top of Sequel core. Each model class is backed by a dataset instance, and many dataset methods can be called directly on the class. Model datasets return rows as model instances, which have fairly standard ORM instance behavior.&lt;br /&gt;
&lt;br /&gt;
Sequel::Model is built completely out of plugins. Plugins can override any class, instance, or dataset method defined by a previous plugin and call super to get the default behavior&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
&lt;br /&gt;
*Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL *queries and table schemas.&lt;br /&gt;
*Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
*Sequel supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.&lt;br /&gt;
*Sequel currently has adapters for ADO, Amalgalite, CUBRID, DataObjects, DB2, DBI, Firebird, IBM_DB, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, Swift, and TinyTDS.[sequel.rubyforge]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class CreateUser &amp;lt; Sequel::Migration&lt;br /&gt;
  def up&lt;br /&gt;
    create_table(:user) {&lt;br /&gt;
      primary_key :id&lt;br /&gt;
      String :name&lt;br /&gt;
      String :age&lt;br /&gt;
      String :email}&lt;br /&gt;
  end&lt;br /&gt;
  def down&lt;br /&gt;
    drop_table(:user)&lt;br /&gt;
  end&lt;br /&gt;
end # CreateUser.apply(DB, :up)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Sequel supports associations and validations similar to Active Record. The following example shows how validations and associations can be enforced in the User table that has been created above. It enforces one to many relationships between the user table and the cheers and posts tables. It also validates for the presence , uniqueness and the length of the attribute '''name'''.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User &amp;lt; Sequel::Model&lt;br /&gt;
  one_to_many :cheers&lt;br /&gt;
  one_to_many :posts&lt;br /&gt;
  &lt;br /&gt;
  validates_presence [:name, :age]&lt;br /&gt;
  validates_unique(:name)&lt;br /&gt;
  validates_length_range 3..20, :name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To access the data in Sequel, one can use where clauses. For instance, to find Bob again one would use DB[:items].where(Sequel.like(:name, 'Bob'). While the ability to use SQL-like where clauses is quite flexible, it is not quite as pure an object-oriented approach as Active Record's dynamically created find methods.&lt;br /&gt;
&lt;br /&gt;
=DataMapper=&lt;br /&gt;
DataMapper is an Object Relational Mapper written in Ruby. The goal is to create an ORM which is fast, thread-safe and feature rich.&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.[datamapper.org]&lt;br /&gt;
&lt;br /&gt;
=Features=&lt;br /&gt;
*Eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
*Lazy loading of select properties, e.g., larger fields&lt;br /&gt;
*Query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
*An API not too heavily oriented to SQL databases&lt;br /&gt;
DataMapper was designed to be a more abstract ORM, not strictly SQL, based on Martin Fowler's enterprise pattern.[2] As a result, DataMapper adapters have been built for other non-SQL databases, such as CouchDB,[3] Apache Solr,[4] and web services such as Salesforce.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Example of table definition in the model:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class User&lt;br /&gt;
  include DataMapper::Resource&lt;br /&gt;
&lt;br /&gt;
  property :id,         Serial    # key&lt;br /&gt;
  property :name,       String, :required =&amp;gt; true, :unique =&amp;gt; true     &lt;br /&gt;
  property :age,        String, :required =&amp;gt; true, :length =&amp;gt; 3..20 &lt;br /&gt;
  property :email,      String &lt;br /&gt;
  &lt;br /&gt;
  has n, :posts          # one to many association&lt;br /&gt;
  has n, :cheers          # one to many association&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Notice that in the example above , &amp;quot;:required = true&amp;quot; is an example for Auto Validation. Unlike ActiveRecord and Sequel, DataMapper supports auto validations , i.e. these in turn call the validation helpers to enforce basic validations such as length, uniqueness, format, presence etc.&lt;br /&gt;
&lt;br /&gt;
=Squeel=&lt;br /&gt;
Squeel unlocks the power of Arel in your Rails 3 application with a handy block-based syntax. You can write subqueries, access named functions provided by your RDBMS, and more, all without writing SQL strings. Squeel acts as an add on to Active Record and makes it easier to write queries with fewer strings.&lt;br /&gt;
A simple example is as follows:&lt;br /&gt;
Squeel lets you rewrite&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where ['created_at &amp;gt;= ?', 2.weeks.ago]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
as&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Article.where{created_at &amp;gt;= 2.weeks.ago}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=MyBatis/iBatis=&lt;br /&gt;
iBATIS was a persistence framework which allowed easy access of the database from a Rails application without being a full ORM. It was created by the Apache Foundation in 2002, and is available for several platforms, including Ruby (the Ruby release is known as RBatis). On 6/16/2010, after releasing iBATIS 3.0, the project team moved from Apache to Google Code, changed the project's name to MyBatis, and stopped supporting Ruby.&lt;br /&gt;
&lt;br /&gt;
The MyBatis data mapper framework makes it easier to use a relational database with object-oriented applications. MyBatis couples objects with stored procedures or SQL statements using a XML descriptor. To use the MyBatis data mapper,we make use of our own objects, XML, and SQL.&lt;br /&gt;
&lt;br /&gt;
SQL statements are stored in XML files or annotations. Follows below a MyBatis mapper, that consist on a Java interface with some MyBatis annotations:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
package org.mybatis.example;&lt;br /&gt;
 &lt;br /&gt;
public interface BlogMapper {&lt;br /&gt;
    @Select(&amp;quot;select * from Blog where id = #{id}&amp;quot;)&lt;br /&gt;
    Blog selectBlog(int id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
The sentence is executed as follows.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
BlogMapper mapper = session.getMapper(BlogMapper.class);&lt;br /&gt;
Blog blog = mapper.selectBlog(101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It can also be executed using MyBatis API.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Blog blog = session.selectOne(&amp;quot;org.mybatis.example.BlogMapper.selectBlog&amp;quot;, 101);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
SQL statements and mappings can also be externalized to an XML file like this.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;UTF-8&amp;quot; ?&amp;gt;&lt;br /&gt;
&amp;lt;!DOCTYPE mapper PUBLIC &amp;quot;-//mybatis.org//DTD Mapper 3.0//EN&amp;quot; &amp;quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&amp;quot;&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;mapper namespace=&amp;quot;org.mybatis.example.BlogMapper&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;select id=&amp;quot;selectBlog&amp;quot; parameterType=&amp;quot;int&amp;quot; resultType=&amp;quot;Blog&amp;quot;&amp;gt;&lt;br /&gt;
        select * from Blog where id = #{id}&lt;br /&gt;
    &amp;lt;/select&amp;gt;&lt;br /&gt;
&amp;lt;/mapper&amp;gt;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
=Comparison of ORM Features=&lt;br /&gt;
&lt;br /&gt;
{|cellspacing=&amp;quot;0&amp;quot; border=&amp;quot;1&amp;quot;&lt;br /&gt;
!style=&amp;quot;width:8%&amp;quot;|Features &lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|ActiveRecord&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|Sequel&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|DataMapper&lt;br /&gt;
!style=&amp;quot;width:23%&amp;quot;|MyBatis&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Databases &amp;lt;/p&amp;gt;&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
| ADO, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, ODBC, OpenBase, Oracle, PostgreSQL and SQLite3&lt;br /&gt;
| SQLite, MySQL, PostgreSQL, Oracle, MongoDB, SimpleDB, many others, including CouchDB, Apache Solr, Google Data API&lt;br /&gt;
| MySQL, PostgreSQL, SQLite, Oracle, SQLServer, and DB2&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Migrations &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes&lt;br /&gt;
| Yes, but optional&lt;br /&gt;
| Yes, provides migration by Mybatis schema migration system.&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; EagerLoading &amp;lt;/p&amp;gt;&lt;br /&gt;
| Supported by scanning the SQL fragments&lt;br /&gt;
| Supported using eager (preloading) and eager_graph (joins) &lt;br /&gt;
| Strategic Eager Loading and by using :summary&lt;br /&gt;
| Yes.this can be enabled or disabled by setting the lazyLoadingEnabled flag&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Flexible Overriding &amp;lt;/p&amp;gt;&lt;br /&gt;
| No. Overriding is done using alias methods.&lt;br /&gt;
| Using methods and by calling 'super'&lt;br /&gt;
| Using methods&lt;br /&gt;
| No&lt;br /&gt;
|-&lt;br /&gt;
! &amp;lt;p align=&amp;quot;left&amp;quot;&amp;gt; Dynamic Finders &amp;lt;/p&amp;gt;&lt;br /&gt;
| Yes. Uses 'Method Missing'&lt;br /&gt;
| No. Alternative is to use &amp;lt;Model&amp;gt;.FindOrCreate(:name=&amp;gt;&amp;quot;John&amp;quot;)&lt;br /&gt;
| Yes. Using the dm_ar_finders plugin&lt;br /&gt;
| Similar feature is supported in the form of Dynamic SQL&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=NonSQL databases:=&lt;br /&gt;
Instead of ORM we can also use OODBMS or document oriented database like XML, where in databases are designed to store object oriented values, thus eliminating the need to convert data to and from its SQL form.&lt;br /&gt;
Document oriented databases also eliminates the user from retrieving  objects as data rows.Query languages like XQuery can be used to retrieve data sets.&lt;br /&gt;
&lt;br /&gt;
The only issue is we won't be able to create application independent queries for retrieving data without restrictions to access path.Also OODBMS limits the extent of processing SQL queries.A relational database allows concurrent access to data, locking, indexing (fast search), as well as many other features that are not in XML file. [http://programmers.stackexchange.com/questions/124976/why-are-sql-databases-still-used-with-orm]&lt;br /&gt;
&lt;br /&gt;
Other OODBMS (such as RavenDB) provide replication to SQL databases, as a means of addressing the need for ad hoc queries, while preserving the increased performance and reduced complexity that may be achieved with an OODBMS for an application that has well-known query patterns.[wikipedia]&lt;br /&gt;
&lt;br /&gt;
NoSQL databases don’t provide mechanism to maintain relationship between tables. In real life though, business objects or entities do have relationship among them. ORM solutions may allow you to define these relationships in business objects and handle their storage and retrieval behind the scene&lt;br /&gt;
&lt;br /&gt;
=Advantages=&lt;br /&gt;
[http://blogs.msdn.com/b/gblock/archive/2006/10/26/ten-advantages-of-an-orm.aspx]&lt;br /&gt;
*Facilitates implementing the Domain Model pattern that allows you to model entities based on real business concepts rather than based on our database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.&lt;br /&gt;
&lt;br /&gt;
*Huge reduction in code. Ease of use, faster development, increased productivity.&lt;br /&gt;
ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.&lt;br /&gt;
&lt;br /&gt;
*Changes to the object model are made in one place. One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.&lt;br /&gt;
&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.&lt;br /&gt;
&lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a Post and you want to access it's Comment, you can simply access Post.Comment and the ORM will take care of loading the data for you without any effort on your part.&lt;br /&gt;
&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of objects without any of it's child / related objects, while in other scenarios you can specify to load an object, with all it's children etc.&lt;br /&gt;
&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
&lt;br /&gt;
*Cache management. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
&lt;br /&gt;
*Transaction management and Isolation. All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.&lt;br /&gt;
&lt;br /&gt;
*Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to.&lt;br /&gt;
&lt;br /&gt;
=Disadvantages=&lt;br /&gt;
[http://www.codefutures.com/weblog/andygrove/archives/2005/02/data_access_obj.html][wikipedia]&lt;br /&gt;
*High level of abstraction obscures as to what is actually happening in the code implementation.&lt;br /&gt;
*Loss in developer productivity whilst they learn to program with ORM.Developers lose understanding of what the code is actually doing - the developer is more in control using SQL.&lt;br /&gt;
*Heavy reliance on ORM also leads to poorly designed databases.&lt;br /&gt;
*Data and behaviour are not separated.&lt;br /&gt;
**Façade needs to be built if the data model is to be made available in a distributed architecture.&lt;br /&gt;
**Each ORM technology/product has a different set of APIs and porting code between them is not easy.&lt;br /&gt;
*The biggest advantage of ORM is also the biggest disadvantage: queries are generated automatically -&lt;br /&gt;
**queries can’t be optimized.&lt;br /&gt;
**queries select more data than needed, things get slower, more latency.&lt;br /&gt;
**compiling queries from ORM code is slow (ORM compiler written in PHP).&lt;br /&gt;
**SQL is more powerful than ORM query languages.&lt;br /&gt;
**database abstraction forbids vendor specific optimizations.&lt;br /&gt;
=Further Reading=&lt;br /&gt;
To get more information on ORM and the different type of ORM's available for Ruby , please look into the [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3j_KS Object-relational mapping Fall 2010] and [http://wiki.expertiza.ncsu.edu/index.php/CSC/ECE_517_Fall_2010/ch3_3f_ac Fall 2010 detailed ORM explanation] wiki pages.&lt;br /&gt;
=Future Work=&lt;br /&gt;
More work can be done in the area of comparison between the different ORMs available for Ruby, especially a more detailed feature-by-feature comparison that includes performance differences between the ORMs.Also, a detailed study of alternatives to ORM like the NoSQL databases and Document-oriented approach can be included.&lt;br /&gt;
=References=&lt;br /&gt;
&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_mapping Wikipedia, Object-relational mapping (ORM)]&lt;br /&gt;
# [http://docforge.com/wiki/Object-relational_mapping , Object-relational mapping]&lt;br /&gt;
# [http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch Object-Relational Impedance&lt;br /&gt;
Matching Problem]&lt;br /&gt;
# [http://www.hibernate.org/about/orm , The Object-Relational Impedance Mismatch]&lt;br /&gt;
# [http://edgeguides.rubyonrails.org/active_record_basics.html#object-relational-mapping , Active Record]&lt;/div&gt;</summary>
		<author><name>Mrsreena</name></author>
	</entry>
</feed>