<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Noupe &#187; Ruby</title>
	<atom:link href="http://www.noupe.com/tag/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://www.noupe.com</link>
	<description>The Curious Side of Smashing Magazine</description>
	<lastBuildDate>Fri, 10 Feb 2012 20:55:07 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>A Simple Twitter App with Ruby on Rails – Building Friendships</title>
		<link>http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-building-friendships.html</link>
		<comments>http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-building-friendships.html#comments</comments>
		<pubDate>Thu, 13 Aug 2009 01:41:05 +0000</pubDate>
		<dc:creator>Editorial</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.noupe.com/?p=19960</guid>
		<description><![CDATA[<table width="650"><tr><td width="650"><div style="width:650px;">
      <img src="http://statisches.auslieferung.commindo-media-ressourcen.de/advertisement.gif" alt="" border="0" /><br />
      <a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=1" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=1" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=2" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=2" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=3" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=3" border="0" alt="" /></a>
    </div></td></tr></table>
<p><a href="http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-building-friendships.html"><img src="http://media.noupe.com//uploads/2009/08/friends.jpg" title="A Simple Twitter App with Ruby on Rails – Building Friendships" width="550" /></a></p>
<p>This is the third and final part of series on how to create a twitter style web application with Ruby on Rails.  This part will cover how to add friendships between users.</p>]]></description>
			<content:encoded><![CDATA[<table width="650">
<tr>
<td width="650">
<div style="width:650px;">
      <img src="http://statisches.auslieferung.commindo-media-ressourcen.de/advertisement.gif" alt="" border="0" /><br />
      <a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=1" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=1" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=2" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=2" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=3" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=3" border="0" alt="" /></a>
    </div>
</td>
</tr>
</table>
<h3 class="title">Introduction</h3>
<p>This is the third and final part of series on how to create a twitter style web application with Ruby on Rails.  This part will cover how to add friendships between users.</p>
<ul class="post">
<li>The <strong>first part </strong>of this tutorial: <a href="http://www.noupe.com/ajax/create-a-simple-twitter-app.html">A Simple Twitter App with Ruby on Rails – Messages With Ajax</a></li>
<li>The <strong>second part </strong>of this tutorial: <a href="http://www.noupe.com/ror/a-simple-twitter-app-with-ruby-on-rails-user-authentication.html">A Simple Twitter App with Ruby on Rails – User Authentication</a></li>
</ul>
<p><span id="more-19960"></span></p>
<h3 class="title">Self-Referential Relationship</h3>
<p class="img"><img src="http://noupe.com/img/ror3/friends.jpg" alt="Friends"/></p>
<p>To create friendships between users we have to deal with a special type of association, which is called a self referential relationship.  It is called this because the model (in this case, User) references itself.  Why?  Well if a given &#8220;user&#8221; has many &#8220;friends&#8221;, those &#8220;friends&#8221; are also &#8220;users&#8221;.  Furthermore, each of those friends can also have friends, so we are dealing with a many to many relationship.</p>
<p>The relationship can affectively be called a &#8220;friendship&#8221; because friendships can be gained and lost (as in real life).  So, let&#8217;s create the friendship model with two foreign keys.</p>
<pre name="code" class="php">

  > ruby script/generate model friendship user_id:integer friend_id:integer
</pre>
<p>Now, migrate the database:-</p>
<pre name="code" class="php">
  > rake db:migrate
</pre>
<h3 class="title">Making and Losing Friends</h3>
<p class="img"><img src="http://noupe.com/img/ror3/relationship.jpg" alt="Making Friends"/></p>
<p>We will need to create and destroy friendships and for this we will need a controller for friendships:-</p>
<pre name="code" class="php">
  > ruby script/generate controller friendships
</pre>
<p>Now add the create and destroy methods as shown below:-</p>
<pre name="code" class="php">
class FriendshipsController < ApplicationController
  def create
    @friendship = current_user.friendships.build(:friend_id => params[:friend_id])
    if @friendship.save
      flash[:notice] = "Added friend."
      redirect_to root_url
    else
      flash[:error] = "Error occurred when adding friend."
      redirect_to root_url
    end
  end

  def destroy
    @friendship = current_user.friendships.find(params[:id])
    @friendship.destroy
    flash[:notice] = "Successfully destroyed friendship."
    redirect_to root_url
  end
end
</pre>
<p class="img"><img src="http://noupe.com/img/ror3/makefriends.png" alt="Making Friends Page"/></p>
<p>So, what exactly do we relate the user model to??  Well, first we need to specify that the friendship model belongs to a friend (which is actually a user!).  You can do this by adding some more lines to the user model:-</p>
<pre name="code" class="php">
class Friendship < ActiveRecord::Base
  ...
  belongs_to :friend, :class_name => "User"
end
</pre>
<p>We need to add two lines to the User model.  A User has many friendships and has many friends through friendships.  This reads almost exactly as it is coded, which is a testament to Ruby on Rails.</p>
<pre name="code" class="php">
class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
  ...
end
</pre>
<h3 class="title">Listing your Friends</h3>
<p class="img"><img src="http://noupe.com/img/ror3/crowd.jpg" alt="List Friends"/></p>
<p>If we want to list all the registered users and allow the current user to befriend other users, then we will need to create a new view in the users folder called index.html.erb:-</p>
<pre name="code" class="php">
<div id="users">
  < % @users.each do |user| %>
<div id="user">
      < % if user.username != current_user.username %>
        < %=h user.username %>
        < %= link_to "Add Friend", friendships_path(:friend_id => user), :method => :post %>
      < % end %>
    </div>

  < % end %>
</div>
</pre>
<p class="img"><img src="http://noupe.com/img/ror3/listfriends.png" alt="Listing Friends Page"/></p>
<p>Now, let&#8217;s put the controller actions in place.  Open the users_controller file and add the index and show methods.</p>
<pre name="code" class="php">
class UsersController < ApplicationController
  def index
    @users = User.all
  end

  def show
    @user = current_user
  end
  ...
end
</pre>
<p>We need to do two more things before we can give this a whirl.  First add the friendships resource to the routes file:-</p>
</pre>
<pre name="code" class="php">
map.resources :friendships
</pre>
<p>&#8230;and finally, we can add some links on the posts/index.html.erb file:-</p>
<pre name="code" class="php">
...

< %= link_to "Make Friends", users_path %>

< %= link_to "My Friends", { :controller => "users", :action => "show", :id => current_user } %>
</pre>
<p>Ok, we can now start up the server and browse to http://localhost:3000 to have a look.</p>
<p class="img"><img src="http://noupe.com/img/ror3/home.png" alt="Home Page"/></p>
<h3 class="title">Summary</h3>
<p>Obviously there are several directions you could take this application.  A lot of features could be added and it could be spruced up, somewhat.  I hope these tutorials have helped you in some way and again, I would highly recommend that you try Ruby on Rails, if you haven&#8217;t already.</p>
<div class="author-box">
<div class="author-text">
<img height="80" width="80" class="author-photo" src="http://media.noupe.com//uploads/2009/06/phil_mcclure_small.jpg" alt=""/>   </p>
<h4><strong>Author</strong>: <a href="http://therailworld.com">Phil McClure</a></h4>
<p>Phil McClure is a Software Developer from Belfast, Northern Ireland. His main interests are software architecture, design patterns and how these can be applied to web development. Phil blogs at <a href="http://therailworld.com">Therailworld</a>. Follow him on <a href="http://www.twitter.com/overture8">Twitter</a>.</p>
</p></div>
<div class="write-for-us"><strong class="red">Write for Us!</strong> We are looking for exciting and creative articles, if you want to contribute, just send us an <a href="mailto:info@noupe.com">email</a>.</div>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-building-friendships.html/feed</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>A Simple Twitter App with Ruby on Rails &#8211; User Authentication</title>
		<link>http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-user-authentication.html</link>
		<comments>http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-user-authentication.html#comments</comments>
		<pubDate>Thu, 16 Jul 2009 02:58:35 +0000</pubDate>
		<dc:creator>Editorial</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[forms]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.noupe.com/?p=17052</guid>
		<description><![CDATA[<table width="650"><tr><td width="650"><div style="width:650px;">
      <img src="http://statisches.auslieferung.commindo-media-ressourcen.de/advertisement.gif" alt="" border="0" /><br />
      <a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=1" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=1" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=2" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=2" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=3" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=3" border="0" alt="" /></a>
    </div></td></tr></table>
<p><a href="http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-user-authentication.html"><img src="http://media.noupe.com//uploads/2009/07/authentication.jpg" title="A Simple Twitter App with Ruby on Rails - User Authentication" width="550"/></a></p>
<p>This article is the second part in a three part series.  In the first part we created some basic functionality to allow the user to post messages in a similar way to Twitter.  If you have not completed the <a href="http://www.noupe.com/ajax/create-a-simple-twitter-app.html">first part of this tutorial</a>, please do so now.</p>]]></description>
			<content:encoded><![CDATA[<table width="650">
<tr>
<td width="650">
<div style="width:650px;">
      <img src="http://statisches.auslieferung.commindo-media-ressourcen.de/advertisement.gif" alt="" border="0" /><br />
      <a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=1" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=1" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=2" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=2" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=3" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=3" border="0" alt="" /></a>
    </div>
</td>
</tr>
</table>
<p>This article is the second part in a three part series.  In the first part we created some basic functionality to allow the user to post messages in a similar way to Twitter.  If you have not completed the <a href="http://www.noupe.com/ajax/create-a-simple-twitter-app.html">first part of this tutorial</a>, please do so now.</p>
<p>In this instalment, we will learn how to add some basic user authentication using a useful plugin called <a href="http://github.com/ryanb/nifty-generators/tree/master">nifty_generators</a>.  So lets get started!</p>
<p><span id="more-17052"></span></p>
<ul class="post">
<li>The <strong>first part </strong>of this tutorial: <a href="http://www.noupe.com/ajax/create-a-simple-twitter-app.html">A Simple Twitter App with Ruby on Rails &#8211; Messages With Ajax</a></li>
<li>The <strong>third part </strong>of this tutorial: <a href="http://www.noupe.com/ror/a-simple-twitter-app-with-ruby-on-rails-building-friendships.html"> A Simple Twitter App with Ruby on Rails – Building Friendships</a></li>
</ul>
<h3 class="title">Get the Gem!</h3>
<p class="img"><img src="http://noupe.com/img/ror/gems.jpg" alt="nifty_generators Gem"/></p>
<p>The <a href="http://github.com/ryanb/nifty-generators/tree/master">nifty_generators</a> gem was created by Ryan Bates, better known for his great <a href="http://railscasts.com/">RailsCast tutorials</a>.  It provides a useful generator for setting up user authentication in a few simple steps.</p>
<p>It&#8217;s worth noting that there are other tools for integrating authentication, for instance <a href="http://github.com/technoweenie/restful-authentication/tree/master">technoweenie&#8217;s Restful Authentication</a> is very good.  However, to keep things simple, we will stick with nifty_generators.</p>
<p>At a command prompt key the following command:-</p>
<pre name="code" class="php">
  > gem install nifty-generators
</pre>
<h3 class="title">Generating the Authentication</h3>
<p class="img"><img src="http://noupe.com/img/ror/authentication.jpg" alt="Authentication"/></p>
<p>Now, make sure your current directory is set to the project folder of your Rails project and run the following commands:-</p>
<pre name="code" class="php">
  > ruby script/generate nifty_authentication
  > ruby script/generate nifty_layout
</pre>
<p>The first command creates the relevant files for achieving authentication.  The second command creates, among other things, a helper file which is required for some of the authentication view files to function correctly.</p>
<p>Don&#8217;t forget to migrate your database!</p>
<pre name="code" class="php">
  > rake db:migrate
</pre>
<h3 class="title">Making use of the Authentication Module</h3>
<p class="img"><img src="http://noupe.com/img/ror/make_use_of_auth.jpg" alt="Authentication"/></p>
<p>Ok, so we now have the functionality, which is required for authenticating users, it&#8217;s just a matter of using it.  First, we will create a <a href="http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials">partial</a> allowing the user to sign up or login.</p>
<p>Create a file called <b>&#8220;_login.html.erb&#8221;</b> in the views/users folder and add the following code:</p>
<pre name="code" class="php">
< % if logged_in? %>
  Welcome < %= current_user.username %>! Not you?
  < %= link_to "Log out", logout_path %>
< % else %>
  < %= link_to "Sign up", signup_path %> or
  < %= link_to "log in", login_path %>.

< % end %>
</pre>
<p>We will simply render the login partial in the <b>&#8220;posts.html.erb&#8221;</b> layout file (to keep things simple).  This file is located in the views/layouts folder.  Edit the file to include the &#8220;render&#8221; method call, as shown below.</p>
<pre name="code" class="php">
.
.
&lt;body&gt;
  &lt;div id="content"&gt;
    &lt;p&gt;&lt;%= render :partial =&gt; "users/login" %&gt;&lt;/p&gt;

    &lt;%= yield %&gt;
  &lt;/div&gt;
&lt;/body&gt;
.
.
</pre>
<p>Further to this, we only want users to be able to post messages if they are logged in so change the <b>&#8220;_message_form.html.erb&#8221;</b> file, in the views/posts folder, to have the following condition:</p>
<pre name="code" class="php">
&lt;% if logged_in? %&gt;

  &lt;% form_remote_tag(:controller =&gt; "posts", :action =&gt; "create") do %&gt;
    &lt;%= label_tag(:message, "What are you doing?") %&gt;&lt;br /&gt;
    &lt;%= text_area_tag(:message, nil, :size =&gt; "60x2") %&gt;&lt;br /&gt;
    &lt;%= submit_tag("Update") %&gt;

  &lt;% end %&gt;
&lt;% end %&gt;
</pre>
<h3 class="title">Let&#8217;s Give it a Go!</h3>
<p>Fire up the server.</p>
<pre name="code" class="php">
  > ruby script/server
</pre>
<p>On the home page we now have &#8220;Sign up&#8221; and &#8220;Login&#8221; links.</p>
<p class="img"><img src="http://noupe.com/img/ror/login_links.jpg" alt="Sign Up and Login Links"/></p>
<p>You&#8217;ll also notice that you cannot post a message until you have a user account.  So you will need to sign up first</p>
<p class="img"><img src="http://noupe.com/img/ror/signup.jpg" alt="Sign Up Form"/></p>
<p>Then you can login&#8230;</p>
<p class="img"><img src="http://noupe.com/img/ror/login.jpg" alt="Our Twitter login page"/></p>
<p>Once you have logged in, you will be able to post messages again.</p>
<p class="img"><img src="http://noupe.com/img/ror/loggedin.jpg" alt="Logged in to our Twitter"/></p>
<p class="img" style="padding: 20px; background-color: rgb(240, 238, 230);"><a style="border: medium none ;" href="http://therailworld.com/posts/18-Create-a-Twitter-App-with-Rails-Demo-Data" target="_blank">View Demo of Twitter App with Ruby on Rails</a></p>
<h3 class="title">Summary</h3>
<p>In this tutorial, you have leanrt how to integrate authentication into your applications and how to make use of it.  In the third and final part of this series you will learn how to add functionality, which allows users to follow other users.</p>
<div class="author-box">
<div class="author-text">
<img height="80" width="80" class="author-photo" src="http://media.noupe.com//uploads/2009/06/phil_mcclure_small.jpg" alt=""/>   </p>
<h4><strong>Author</strong>: <a href="http://therailworld.com">Phil McClure</a></h4>
<p>Phil McClure is a Software Developer from Belfast, Northern Ireland. His main interests are software architecture, design patterns and how these can be applied to web development. Phil blogs at <a href="http://therailworld.com">Therailworld</a>. Follow him on <a href="http://www.twitter.com/overture8">Twitter</a>.</p>
</p></div>
<div class="write-for-us"><strong class="red">Write for Us!</strong> We are looking for exciting and creative articles, if you want to contribute, just send us an <a href="mailto:info@noupe.com">email</a>.</div>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.noupe.com/ajax/a-simple-twitter-app-with-ruby-on-rails-user-authentication.html/feed</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
		<item>
		<title>A Simple Twitter App with Ruby on Rails &#8211; Messages With Ajax</title>
		<link>http://www.noupe.com/ajax/create-a-simple-twitter-app.html</link>
		<comments>http://www.noupe.com/ajax/create-a-simple-twitter-app.html#comments</comments>
		<pubDate>Wed, 24 Jun 2009 01:01:11 +0000</pubDate>
		<dc:creator>Editorial</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.noupe.com/?p=14323</guid>
		<description><![CDATA[<table width="650"><tr><td width="650"><div style="width:650px;">
      <img src="http://statisches.auslieferung.commindo-media-ressourcen.de/advertisement.gif" alt="" border="0" /><br />
      <a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=1" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=1" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=2" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=2" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&collection=noupe-rss&position=3" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&collection=noupe-rss&position=3" border="0" alt="" /></a>
    </div></td></tr></table>
<p><a href="http://www.noupe.com/ajax/create-a-simple-twitter-app.html"><img src="http://media.noupe.com//uploads/2009/06/messages.jpg" title="A Simple Twitter App with Ruby on Rails - Messages With Ajax" width="550"/></a></p>
<p>Ruby on Rails is a web application framework that promotes rapid development.  Clients' demands are ever increasing yet they still expect the same quality of output.</p>]]></description>
			<content:encoded><![CDATA[<table width="650">
<tr>
<td width="650">
<div style="width:650px;">
      <img src="http://statisches.auslieferung.commindo-media-ressourcen.de/advertisement.gif" alt="" border="0" /><br />
      <a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=1" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=1" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=2" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=2" border="0" alt="" /></a>&nbsp;<a href="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=target&#038;collection=noupe-rss&#038;position=3" target="_blank"><img src="http://auslieferung.commindo-media-ressourcen.de/random.php?mode=image&#038;collection=noupe-rss&#038;position=3" border="0" alt="" /></a>
    </div>
</td>
</tr>
</table>
<p>Ruby on Rails is a web application framework that promotes rapid development.  Clients&#8217; demands are ever increasing yet they still expect the same quality of output. </p>
<p> Frameworks, like Rails, help to achieve this; why?&#8230; here are some of the reasons:</p>
<ul class="post">
<li>The <strong>second part </strong>of this tutorial: <a href="http://www.noupe.com/ror/a-simple-twitter-app-with-ruby-on-rails-user-authentication.html">A Simple Twitter App with Ruby on Rails – User Authentication</a></li>
<li>The <strong>third part </strong>of this tutorial: <a href="http://www.noupe.com/ror/a-simple-twitter-app-with-ruby-on-rails-building-friendships.html"> A Simple Twitter App with Ruby on Rails – Building Friendships</a></li>
</ul>
<hr /><span id="more-14323"></span></p>
<ul class="post">
<li><strong>Convention over Configuration (CoC): </strong><br />
<hr />This is used to reduce the amount of up-front configuartion.  The idea is; if you abide by certain coding conventions, you will have little, to none, configuration to do.</li>
<li><strong>Object-Relational Mapping (ORM):</strong><br />
<hr />ORM reducing coupling to the database.  This abstraction allows you changed the DBMS provider with little trouble.</li>
<li><strong>Structured Code:</strong><br />
<hr />The MVC pattern forces you to organise your code in a clean, structured way.  This results in more maintainable code.</li>
<li><strong>Plugins:</strong><br />
<hr />Plugins save you from re-inventing the wheel every time you want to add functionality to your app.  For instance, making you web app capable of performing searches can be easily added with the acts_as_ferret plugin.  There are many more plugins!</li>
</ul>
<p class="img"><img src="http://noupe.com/img/ruby1/twitterblog.jpg" alt=""/></p>
<h3 class="title">Who is this Tutorial for?</h3>
<p>This tutorial is for people who have learnt the basics of Rails and want to take things to the next level.  This tutorial is not a beginners guide for getting started with Rails.  If you are just starting out with Rails I suggest this <a href="http://sixrevisions.com/web-development/how-to-create-a-blog-from-scratch-using-ruby-on-rails/">article from Six Revisions</a>.</p>
<h3 class="title">What this Tutorial Covers</h3>
<p>In the first part of this three part series, we cover setting up a simple message model, which will hold the messages posted.  Further to this, we will learn how to post a message asynchronously, using AJAX.</p>
<p style="background-color:#F0EEE6;<br />
border:1px solid #E7E5DD; padding:20px" class="img"><a target="_blank" href="http://www.therailworld.com/posts/18-Create-a-Twitter-App-with-Rails-Demo-Data" style="border:none">View Demo of Twitter App with Ruby on Rails</a></p>
<h3 class="title">Basic Application Design</h3>
<p class="img"><img src="http://noupe.com/img/ruby1/webdesign.jpg" alt=""/></p>
<p>Ok, so you&#8217;ve decided to create a &#8220;twitter&#8221; style micro-blog using Ruby on Rails.  First, we need to think about our basic requirements and from this we can model our application.</p>
<p>There are many ways that this can be done, but we will use a simple technique in which you jot down a few paragraphs about how and what the application is expected to do then highlight the nouns.  So, lets try it.</p>
<p><i>My web app should work in a similar way to twitter.  <b>Users</b> should be able to register with the site and create short <b>posts</b>.  Users should be able to follow other users.  Each user should be able to see their own posts plus the users they are following.</i></p>
<p>Note that I&#8217;ve been selective in what nouns I&#8217;ve highlighted.  You only really need to take notice of the nouns which you feel will need to store data to the database.</p>
<p>I know there is more to twitter than this, but lets leave it simple.  As you can see the &#8220;nouns&#8221;, which will need to store data to the database are &#8220;posts&#8221; and &#8220;users&#8221;.  So we require two models:</p>
<p><b>In the first part of the tutorial, we are going to deal with posts only.</b></p>
<ul>
<li>Post</li>
<li>User</li>
</ul>
<h3 class="title">Creating the Project Files</h3>
<p>Before we do anything we need to create a project for our twitter web app.</p>
<pre name="code" class="javascript">
  > rails twitter -d mysql
</pre>
<p>As you can see, I will be using MySQL as the DBMS, however, feel free to use whatever database you want.</p>
<p>Open the database.yml file in the config folder and modify the password as required.  An example is shown below.</p>
<pre name="code" class="javascript">
development:
  adapter: mysql
  encoding: utf8
  database: twittest_development
  pool: 5
  username: root
  password: yourpassword
  host: localhost
</pre>
<p>Now, create the database with the &#8220;rake&#8221; command.</p>
<pre name="code" class="javascript">
  > rake db:create
</pre>
<h3 class="title">Implementing the basic Message Model</h3>
<p class="img"><img src="http://noupe.com/img/ruby1/messages.jpg" alt=""/></p>
<p>So let&#8217;s go right ahead and generate the &#8220;Post&#8221; model and migrate it.</p>
<pre name="code" class="javascript">
  > ruby script/generate model post message:text
  > rake db:migrate
</pre>
<h3 class="title">Controller</h3>
<p>Now, let&#8217;s create a controller for the post model.</p>
<pre name="code" class="javascript">
  > ruby script/generate controller posts
</pre>
<p>We need to set up some methods for interacting with the model.   Edit your &#8220;posts_controller.rb&#8221; file and add the following methods:</p>
<pre name="code" class="javascript">
class PostsController &lt; ApplicationController
  def index
    @posts = Post.all(:order => "created_at DESC")
    respond_to do |format|
      format.html
    end
  end

  def create
    @post = Post.create(:message => params[:message])
    respond_to do |format|
      if @post.save
        format.html { redirect_to posts_path }
      else
        flash[:notice] = "Message failed to save."
        format.html { redirect_to posts_path }
      end
    end
  end
end
</pre>
<p>We only need two methods, &#8220;index&#8221; and &#8220;create&#8221;.  The index method creates an instance variable containing all the posts in descending order.  The create method is used to create a new post.</p>
<h3 class="title">Views</h3>
<p>Let&#8217;s create the &#8220;index&#8221; view.  First, we&#8217;ll create a partial for posts.  Create a file called &#8220;_post.html.erb&#8221; in the views/posts folder and add the code below.</p>
<pre name="code" class="javascript">
&lt;p&gt;&lt;b&gt;Posted &lt;%= time_ago_in_words(post.created_at) %&gt; ago&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;&lt;%= post.message %&gt;&lt;/p&gt;
</pre>
<p>The index view is now very simple.  Create a file called &#8220;index.html.erb&#8221; in the views/posts folder and add the code below.</p>
<pre name="code" class="javascript">
&lt;%= render :partial =&gt; @posts %&gt;
</pre>
<h3 class="title">Create some Posts</h3>
<p>Open a console session and create a few new messages, as shown below.</p>
<pre name="code" class="javascript">
  > ruby script/console
  Loading development environment (Rails 2.3.2)
  >> Post.create!(:message =&gt; "My first post" )
  >> Post.create!(:message =&gt; "Post number two!" )
</pre>
<h3 class="title">Create a Form for Posts</h3>
<p>Obviously you&#8217;re not going to get the user to use the console to create messages.  So, our next task is to inject some functionality into our web app to allow the user to create messages.  Twitter has an input box above the indexed messages, which is used for submitting a new message;  We will keep our web app the same.</p>
<p>First, we will create a partial for the form, then we will render that partial at the top of the index view.  Create a file called &#8220;_message_form.html.erb&#8221; in the posts view folder and add the following code:</p>
<pre name="code" class="javascript">
&lt;% form_tag(:controller =&gt; "posts", :action =&gt; "create") do %&gt;
  &lt;%= label_tag(:message, "What are you doing?") %>&lt;br /&gt;
  &lt;%= text_area_tag(:message, nil, :size => "44x6") %>&lt;br /&gt;
  &lt;%= submit_tag("Update") %&gt;
&lt;% end %&gt;
</pre>
<p>Now, we need to modify the index view to render this partial at the top.  Open the index.html.erb file and modify the code as follows:</p>
<pre name="code" class="javascript">
<b>< %= render :partial => "message_form" %></b>
< %= render :partial => @posts %>
</pre>
<p>For this to work we need to make one last modification.  Open the route.rb file and map a new &#8220;posts&#8221; resource, as shown below.  (Note: the comments from this file have been removed).</p>
<pre name="code" class="javascript">
ActionController::Routing::Routes.draw do |map|
  map.resources :posts
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end
</pre>
<p>This creates a few named routes.  If you look back to the &#8220;create&#8221; method in the posts controller, you&#8217;ll see that we make use of the posts_path named route; Defining the posts resource makes this named route available.</p>
<p>So, lets fire up the web server and a see how things look.</p>
<pre name="code" class="javascript">
  > ruby script/server
</pre>
<p>Now open a browser and go to http://localhost:3000/posts.  You should see a screen, as shown below.</p>
<p class="img"><img src="http://noupe.com/img/ruby1/twitter1.jpg" alt=""/></p>
<h3 class="title">Adding some AJAX</h3>
<p>AJAX allows you to make asynchronous requests to the server using JavaScript.  We will make use of AJAX to make the posting a message a bit smoother.</p>
<p>When the user clicks on the &#8220;Update&#8221; button, we want the message to update without refreshing the browser.  We have a few things to do to add AJAX functionality.  First, lets change the &#8220;create&#8221; method in the posts controller:</p>
<pre name="code" class="javascript">
  def create
    @post = Post.create(:message => params[:message])
    respond_to do |format|
      if @post.save
        format.html { redirect_to posts_path }
        format.js
      else
        flash[:notice] = "Message failed to save."
        format.html { redirect_to posts_path }
      end
    end
  end
</pre>
<p>The only change here is the &#8220;format.js&#8221; code, allowing the create method to respond to JavaScript.  Next, we need to create a posts layout file.  In the views/layout folder create a file called &#8220;posts.html.erb&#8221; and add the following code:</p>
<pre name="code" class="javascript">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt;
&lt;head&gt;
  &lt;%= javascript_include_tag :all %&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;div id="content"&gt;
    &lt;%= yield %&gt;
  &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The main purpose of this is to make use of the &#8220;javascript_include_tag&#8221; call, which includes the relevant JavaScript files for AJAX and some visual effects.  Next, we need to make a small addition to the index view (&#8220;index.html.erb&#8221;).</p>
<pre name="code" class="javascript">
&lt;%= render :partial =&gt; "message_form" %&gt;
<b>&lt;div id="posts"&gt;</b>
  &lt;%= render :partial =&gt; @posts %&gt;
<b>&lt;/div&gt;</b>
</pre>
<p>As you can see all we have added is a div block surrounding the posts partial.  This will be used later when we are specifying where the AJAX response should be placed.  Nearly there!  Now we will add a div_for block to our post partial (&#8220;_post.html.erb&#8221;).</p>
<pre name="code" class="javascript">
&lt;% div_for post do %&gt;
  &lt;p&gt;&lt;b&gt;Posted &lt;%= time_ago_in_words(post.created_at) %&gt; ago&lt;/b&gt;&lt;/p&gt;
  &lt;p&gt;&lt;%= post.message %&gt;&lt;/p&gt;
&lt;% end %&gt;
</pre>
<p>Edit the &#8220;_message_form.html.erb&#8221; partial and change the form_tag call to form_remote_tag as show in the code extract below:</p>
<pre name="code" class="javascript">
&lt;% form_remote_tag(:controller =&gt; "posts", :action =&gt; "create") do %&gt;
</pre>
<p>The div_for operation create a div block with a unique id, this is especially useful when looping through several records.  Finally, we need to create the rjs template.  To do this, create a file called &#8220;create.js.rjs&#8221; in the views/posts folder and add the following code.</p>
<pre name="code" class="javascript">
page.insert_html :top, :posts, :partial => @post
page[@post].visual_effect :highlight
</pre>
<p>The first line specifies that a new post partial will be rendered at the top of the posts div when the asynchronous call responds.  The second line specifies that a &#8220;highlight&#8221; visual effect will be applied to that block when it is rendered.</p>
<p>That&#8217;s it!  Start you web server again, browse to http://localhost:3000/posts and give it a go.</p>
<h3 class="title">Make it Look Pretty!</h3>
<p class="img"><img src="http://noupe.com/img/ruby1/style.jpg" alt=""/></p>
<p>I&#8217;ve created a stylesheet, which we can use to make things look a bit more respectful.  Create a file called layout.css in the public/stylesheets folder then add the following CSS code:</p>
<pre name="code" class="css">
body
{
  font-family: tahoma, sans-serif;
  font-size: 18px;
  background-color: #4B7399;
  width: 100%;
  color: #ffffff;
  margin: 0;
  text-align: center;
}

#content
{
  width: 800px;
  margin: 0 auto;
  text-align: left;
}

.post
{
  padding: 5px 20px 5px 20px;
  background-color: #ffffff;
  margin: 20px 0 20px 0;
  color: #000000;
}
</pre>
<p>Finally, you will need to add stylesheet_link_tag call to the posts.html.erb layout file.  As per below, the call should be placed in the head tag.</p>
<pre name="code" class="javascript">
&lt;head&gt;
  &lt;%= javascript_include_tag :all %&gt;
  <b>&lt;%= stylesheet_link_tag 'layout' %&gt;</b>
&lt;/head&gt;
</pre>
<p>OK! It doesn&#8217;t look that pretty, but it will do for our purposes.</p>
<p class="img"><img src="http://noupe.com/img/ruby1/twitter2.jpg" alt=""/></p>
<h3 class="title">Setting up a Home Page</h3>
<p>To have the root URL (http://localhost:3000) direct the user towards your posts you will first need to delete the public/index.html file.  Do this now.</p>
<p>The second thing you need to do is set up a route in your config\routes.rb file.  Open routes.rb in notepad and add a new line to the end using map.root, as shown below.</p>
<pre name="code" class="javascript">
ActionController::Routing::Routes.draw do |map|
  map.resources :posts
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
  map.root :controller => "posts"
end
</pre>
<p>For more on routes, try the <a href="http://api.rubyonrails.org/classes/ActionController/Routing.html">Rails API Documentation</a></p>
<p>Now if you browse to http://localhost:3000.  The request will be routed to the posts controller.</p>
<h3 class="title">Summary</h3>
<p>This concludes the first part of the series.  Depending on the popularity of this article, parts 2 and 3 will follow shortly.</p>
<h4 class="title">What have we Learnt?</h4>
<p>You&#8217;ve learnt how to carry out basic application design and how to use this design to work out what models are required.  Further to this, you&#8217;ve learnt how to use the console to help with the development of your application.  Finally, you used AJAX to perform asynchronous requests to the server.</p>
<div class="author-box">
<div class="author-text">
<img height="80" width="80" class="author-photo" src="http://media.noupe.com//uploads/2009/06/phil_mcclure_small.jpg" alt=""/>   </p>
<h4><strong>Author</strong>: <a href="http://therailworld.com">Phil McClure</a></h4>
<p>Phil McClure is a Software Developer from Belfast, Northern Ireland. His main interests are software architecture, design patterns and how these can be applied to web development. Phil blogs at <a href="http://therailworld.com">Therailworld</a>. Follow him on <a href="http://www.twitter.com/overture8">Twitter</a>.</p>
</p></div>
<div class="write-for-us"><strong class="red">Write for Us!</strong> We are looking for exciting and creative articles, if you want to contribute, just send us an <a href="mailto:info@noupe.com">email</a>.</div>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.noupe.com/ajax/create-a-simple-twitter-app.html/feed</wfw:commentRss>
		<slash:comments>84</slash:comments>
		</item>
	</channel>
</rss>

