Fetch contacts from Facebook using Ruby on Rails March 13, 2009
Posted by Puneet Pandey in Ruby On Rails.Tags: Add Facebook friends using ruby on rails, Fetch facebook friends using rails, How to fetch contacts from facebook
add a comment
Volaaaa…. Finally I’ve got the way, how should I fetch contacts from facebook.. I hope everyone is looking for it..
Let me show you how would I do that.
Note: You can’t get your contacts email addresses using this post.
Mandatory Data:
[1] facebooker plugin
[2] Facebook developer application
Now how to do it let’s see:
Install facebooker plugin from Here into your rails application.
If you are done with that go to Facebook, if you have your account there sign-in and then search for developer application, add it if you haven’t added before. Below is the screenshot how you developer application looks like:
Now here you can see a button “Set up New Application” click on that It will led you to a new application page like this:
Give the name of your new application click on Agree and then “Save Changes”, Once your new application is created click on “Edit Settings” link on the right side of the center div.
It will drop you to a new page click on “Canvas” tab and give your “Callback URL” and “Canvas Page URL”.
NOTE: make sure those two fields are not blank and properly accepted by the facebook.
Now “back to My Applications”, you will find that you have following things:
[1] API Key
[2] Application Secret
[3] Callback URL
[4] Canvas URL
Now back into your rails application, after installing the plugin, you will find that a file facebooker.yml has been created for you in the config folder just open that and put all the 4 things inside that wherever it is needed.
Awesome Man!!!!! you are almost done.. just couple of steps short to see it in action
Create a controller for your rails application in my case it is:
ruby script/generate controller GettingStarted
open this file and paste the below lines:
class GettingStartedController < ApplicationController
ensure_authenticated_to_facebook
def index
@user = session[:facebook_session].user
@frnd=@user.friends!(:name, :interests, :status)
end
end
Now open up index.html.erb and paste the below code:
<input type=”textarea” name=”show_code” value=”
Disecting FaceBook With
body{padding:0px;margin:0px;font-family:verdana,Trebuchet MS; font-size:12px; background-color:#eee;}
p.rowA {background-color: #C6DB7C; color:#000000;width:400px; }
p.rowB {background-color: #457AA0;width:400px; }
p{margin:0px; padding:10px;}
#left{width:40%;border:1px solid #eee;float:left; padding:10px;}
#right{width:50%; border:1px solid #eee; float:right; padding:10px;color:white;}
Hey we got you !!
These are the people, you talking with?
<p class=”"> <input type=”checkbox” name=”facebook_friends[]” id=”facebook_friends_” value=”" /> <%= “Friend: #{friend.name}
#{hash}
Interests: #{friend.interests}
” %>
” rows=”10″ cols=”20″>
create another file manually index.fbml.erb and paste the below code:
That’s it.. everything is finished.. start your server
Fetch Rss Feeds in Rails March 2, 2009
Posted by Puneet Pandey in Ruby On Rails.Tags: Fetch feeds in rails, How to fetch rss feeds in rails, rails feeds, Rails Rss feeds, Rss on Ruby on Rails
add a comment
Heya Guys,
Gossshh, I had lot of work, woooooohhh, but now I am over with that and thought to write a new post for all of you… I am very thankful to all of you that you are appreciating my articles and giving me such a good response, It is not only developing my confidence but also I want to bring more and more articles in rails, so that It will help you to know the magic behined RoR.
So let me start it. In this post of mine I will Fetch Rss Feeds from Techcrunch with open-uri, Interested to know, let’s see how it works…
Create an application, open your environment.rb file and add this line at the bottom:
RSS_FEED = ‘http://feedproxy.google.com/TechCrunch’
Now create a controller, in my case I have feeds_controller with fetch method, Open it and add below lines
class FeedsController < ApplicationController
require ‘rss/2.0′
require ‘open-uri’
def fetch
feed_url = “#{RSS_FEED}”
count = 50.to_i
output = “
Rss Reader
“
open(feed_url) do |http|
response = http.read
result = RSS::Parser.parse(response, false)
output += “Reed Title: #{result.channel.title}
“
result.items.each_with_index do |item, i|
output += “#{i+1}. ‘#{item.title}’
” if i output
end
end
You are almost done guys, now open up your views/feeds/fetch.html.erb and write a single line:
That is it. You are done.. start your server and you should see all the feeds there…
like this:
Don’t forget to drop me your inputs, suggestions, feedback on this..
With Love
Puneet
Problem in Installing Contacts GEM in Windows December 23, 2008
Posted by Puneet Pandey in Ruby On Rails.Tags: 'nmake' is not recognized as an internal or external command, gem install contacts is giving error, install contacts gem on windows, nmake error, nmake error while installing gem on windows, problem in installing contacts gem
9 comments
hey guys,
In this post of mine, I will show you how to install ‘contacts’ gem in your windows machine.
God, I searched google a lot for this and at last I found something interesting which I want to tell you.
I was working on linux, I switched to windows recently. During my project I thought to install contacts which will import my contacts from Gmail, Yahoo and Hotmail. When I write in command prompt:
C:\> gem install contacts
it gives me the following error
nmake
‘nmake’ is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6
for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6/ext/gem_make.out
I think lots of you have seen this kind of error, Now I am telling you the steps how to solve this
Concentrate on line this :
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/ferret-0.11.6
Now go to this Url
http://rubyforge.org/frs/?group_id=1028
and install the latest ferret gem having mswin32 version. Install it and run it, I think all of you know how to install gem manually
Then try to install contacts gem, It will run.
Just in case if it gives error again like this:
nmake
‘nmake’ is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/json-1.1.3 for
inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/json-1.1.3/ext/json/ext/parser/
gem_make.out
Then go to this url:
http://rubyforge.org/frs/?group_id=953
and download the latest mswin32 gem of json and install it. After installing it try to run
gem install contacts
Your gem should install.
Generate XML with Rails December 8, 2008
Posted by Puneet Pandey in Ruby On Rails.Tags: generate xml with builder gem, generate xml with rails, how to generate xml with rails, problem in creating XML, XML with rails
3 comments
Hello All,
Happy New Year in Advance, In this post of mine, I will generate XML with Buildergem. Here is how to do this:
go to terminal, in my case I m generating a new application.
–> rails myapp
go into the directory and type
–> mysql -u root -p
This will open mysql query browser in the terminal itself, create a new schema
–> create schema myapp_development;
type –> exit and get out from terminal, open your –> database.yml and change it according to that.
Now, generate a model Address by this:
–> ruby script/generate model Address
now open your addresses.rb from db/migrate folder and add following lines
–> t.string :name
t.string :city
One thing to be noted here, I m using acts_as_authenticated plugin, so I have added user_id also in that, so that It will be easy for me to generate XML for the current_user i.e the logged in user.
run –> rake db:migrate
if you have builder gem installed open up environment.rb file from config folder and add
–> require ‘builder’
after the end the ‘end’ line.
If you don’t have builder, you can easily install it by typing
–> sudo gem install builder
I think you guys are able to generate rhtml pages of it, now let’s see the controller action:
–> def new
@address = Address.new
end

from here my action goes to generate, see how gen_xml will store data.
–> def generate
@address = Address.new(params[:address])
@address.user_id = current_user.id
if @address.save
redirect_to :action => ‘gen_xml’
end
end
values of address are saved, let’s see our new action i.e gen_xml
–> def gen_xml
@xml = Builder::XmlMarkup.new
@addresses = Address.find(:all, :conditions => ["user_id = ?", current_user.id])
render :layout => false
end
Here Builder is your gem and it will generate XmlMarkup, here I m giving render :layout => false, coz I want to display generated XML without any CSS. Now your next step will be to create a file in your controller name gen_xml.rxml and add the below code:
–> xml.instruct!
ml, :version=>”1.0″
xml.declare!
OCTYPE, :html,
UBLIC, “-//W3C//DTD XHTML 1.0 Strict//EN”, “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”
xml.addresses{
for address in @addresses
xml.address do
xml.name(address.name)
xml.city(address.city)
end
end
}
that’s it you are done, below is the screenshot of what I have done:

If you find any problem or if you have done it successfully, please leave a comment. It will give boost up my confidence level.
Thanks
Ruby on Rails Interview Questions October 3, 2008
Posted by Puneet Pandey in Ruby On Rails.Tags: expert ror interview questions, interview questions on ruby on rails, ror interview questions, Ruby on rails interview questions
24 comments
Hi Guys, Hope you all are fine, Well I think that I should Post something different in my blog, so that It will help you to get some more knowledge
, So I came with Interview Questions, Hope this will help you a lot, I will update it regularly, If I found something Interesting. Well If you are experienced, I hope this should help you. All the Questions are dynamically Typed.
Q1. What is request.xhr?
Sol: A request.xhr tells the controller that the new Ajax request has come, It always return TRUE or FALSE
Q2. What is the Difference between Static and Dynamic Scaffolding?
Sol: The Syntax of Static Scaffold is like this:
ruby script/generate scaffold User Comment
Where Comment is the model and User is your controller, So all n all static scaffold takes 2 parameter i.e your controller name and model name, whereas in dynamic scaffolding you have to define controller and model one by one.
Q3. What is the Difference between Symbol and String?
Q4. What is Session and Cookies?
Sol: Session: are used to store user information on the server side.
cookies: are used to store information on the browser side or we can say client side
Session : say session[:user] = “puneet” it remains when the browser is not closed
Q5. Why Ruby on Rails?
Sol: There are lot of advantages of using ruby
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept
Q6. What is MVC? and how it Works?
Sol: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like this: Request first comes to the controller, controller finds and appropriate view, your view interacts with model, model interacts with your database, for Example your url is something like this:
http://localhost:3000/users/new
here users is your controller and new is your method, there must be a file in your views/users folder named new.html.erb, so once the submit button is pressed, User model or whatever defined in the rhtml form_for syntax, will be called and values will be stored into the database.
Q7. What things we can define in the model?
Sol: There are lot of things you can define in models few are:
1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships(like has_one, has_many, HABTM etc.)
3. Callbacks(like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql
Q8. What is ORM in Rails?
Sol: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.
Q9. How many Types of Relationships does a Model has?
Q10. What is the difference between rails version 2.2.2 with the older ones?
Q11. Difference between render and redirect?
Sol: render example: render :action, render :partial etc.
redirect example: redirect_to :controller => ‘users’, :action => ‘new’
Q12. How to use sql db or mysql db. without defining it in the database.yml
Sol. http://stuff.lilleaas.net/active_record_anywhere
Q13. What are helpers and how to use helpers in ROR?
Sol. Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.
Q14. What is Active Record?
Sol. Active Record are like Object Relational Mapping(ORM), where classes are mapped to table and objects are mapped to colums in the table
Q15. Ruby Supports Single Inheritence/Multiple Inheritence or Both?
Sol. Ruby Supports only Single Inheritnece
Q16. How many types of callbacks available in ROR?
Sol. * (-) save
* (-) valid
* (1) before_validation
* (2) before_validation_on_create
* (-) validate
* (-) validate_on_create
* (3) after_validation
* (4) after_validation_on_create
* (5) before_save
* (6) before_create
* (-) create
* (7) after_create
* (8) after_save
Q17. Suppose in one of my method I am updating the attributes of table, in my model I have defined after_create do X, and after_save do Y. Which method will be called?
Ruby Interview Questions :
Q1. How to use two database into a Single Application?
Sol. http://magicmodels.rubyforge.org/magic_multi_connections/, According to this link : ActiveRecord models are allowed one connection to a database at a time, per class. Ruby on Rails sets up the default connection based on your database.yml configuration to automatically select development, test or production.
But, what if you want to access two or more databases – have 2+ connections open – at the same time. ActiveRecord requires that you subclass ActiveRecord::Base.
That prevents you doing migrations from one database to another. It prevents you using one set of model classes on two or more databases with the same schema.
Magic Multi-Connections allows you to write your models once, and use them for multiple Rails databases at the same time. How? Using magical namespacing.
To do this :
[A] sudo gem install magic_multi_connections
[B] require ‘magic_multi_connections’
Add the following to the bottom of your environment.rb file
You can also find examples on this link : http://magicmodels.rubyforge.org/magic_multi_connections/
Q2. What is the Notation used for denoting class variables in Ruby?
Q3. What is the use of Destructive Method?
Q4. What is the use of load and require in Ruby?
Q5. What is the use of Global Variable in Ruby?
Q6. How does nil and false differ?
Q7. How is visibility of methods change in Ruby?
Q8. What is a Class Instance Variable
Q9. What are the rules and conventions to be followed in Ruby for naming a method?
Q10. What is the use of Super?
Q11. How is class method defined in Ruby?
Q12. What are the Operators available in Ruby?
Q13. What are the looping structure available in Ruby?
Q14. What is the scope of local variable?
Q15. What are the OOP supported by Ruby?
Q26. If Ruby over PHP, Why?
Q17. Garbage collection in Ruby?
Q18. Environment Variables in Ruby?
Q19. What are Float, Dig and Max?
Q20. What is Ruby Code blocks?
Q21. What kind of conditions ruby support?
Q22. Difference between puts and print
More Questions and Answers of this will be published very soon
So stay in touch.. I will keep you updating.. if you have some questions please reply…
Fetching Cotacts from Gmail, Yahoo and Hotmail September 26, 2008
Posted by Puneet Pandey in Uncategorized.Tags: contact list importer, contacts a universal gem to fetch contacts, fetch your friend list from gmail, grab contacts from gmail, grab contacts from hotmail, grab contacts from yahoo, grab contacts using contacts gem in rails
63 comments
Hello Guys,
This is another post by me, hope this post will help you, if you are stuck in fetching or grab contacts from Yahoo, Gmail and Hotmail. This is possible using gem ‘contacts’.
So here I am posting my code, I know there are lot of things and code available for this, but this is the exact code which I am using.
If you are running an application or want to create a new go ahead, I am writing a new application here but you can add it in your existing code as well.
open your command or console prompt and go into your application directory, here I am creating new:
rails contact
this will create a particular set of files and directories in your application. Now go into your directory, before start working any further be sure that you have installed ‘contacts’ gem with the latest version i.e 1.0.13, to install ‘contacts’ type :
for linux users : sudo gem install contacts
for windows : gem install contacts
if already have but older version update it : sudo gem update contacts
Now open your environemnt.rb file and below this line write
Rails::Initializer.run do |config|
end
require ‘contacts’
be sure to restart your server.
Now open the controllers folder and create this method in any controller if you have or where you want to display this. In my case I am writing this in my account_controller.rb
def invite_friends
#@user = User.find(params[:id])
end
def import
@users = User.find(params[:id])
begin
@sites = {”gmail” => Contacts::Gmail, “yahoo” => Contacts::Yahoo, “hotmail” => Contacts::Hotmail}
@contacts = @sites[params[:from]].new(params[:login], params[:password]).contacts
@users , @no_users = [], []
@contacts.each do |contact|
#if u = User.find(:first , :conditions => @users.email = ‘#{contact[1]}’ , :include =>[:user])
if u = User.find(:first , :conditions => “email = ‘#{contact[1]}’” )
@users << u
else
@no_users << {:name => contact[0] , :email => contact[1]}
end
end
respond_to do |format|
format.html {render :template => ’shared/_contact_list’, :layout => false}
format.xml {render
ml => @contacts.to_xml}
end
end
before creating this two method, just be sure that you are giving the user id from invite_friends method to import method.
Open up your invite_friends.html.erb and paste this code :
<% form_tag :action => ‘import’, :id => @user do %>
<select name=”from” id=”from”>
<option value=”">Select Id</option>
<option value=”gmail”>Gmail</option>
<option value=”yahoo”>Yahoo</option>
<option value=”hotmail”>Hotmail</option>
</select>
<BR />
<p>Please Enter Your Email Address Below : <BR />
<input type=”text” name=”login”></p>
<p>Enter Your Password :<BR />
<input type=”password” name=”password”></p>
<p><h4>Note : we are not going to save your Password anywhere </h4></p>
<p><%= submit_tag ‘Find My Friends’ %>
<% end %>
Now start your server, open up firefox and type the address (in my case it is) : http://localhost:3000/account/invite_friends
Select any service like Yahoo, Hotmail or Gmail give the corresponding username and Password and hit submit.
You will get an error message that missing template, to remove that create a folder ’shared’ in /app/views/ and create a new file name ‘_contact_list.html.erb’ and paste the below code :
<% for i in @contacts %>
<input type=”checkbox” name=”email[]” id=”email_<%= i %>” value=”<%= i %>” /><%= i %><br>
<% end %>
this will help you to take further actions on fetched email addresses, that’s it. You have done..
If you are facing any problems, leave a comment, I will get back in touch with you, and if your code works, don’t forget to leave a comment.
Thanks to ‘contacts’ and thanks to you all also.
Ruby on Rails Auto Select June 1, 2008
Posted by Puneet Pandey in Ruby On Rails.Tags: Ajax on Rails Auto Complete, cascading drop-down with rails and ajax, How to select College According to City and city accord, ruby on rails auto select, Ruby on Rails with Ajax Auto Select
10 comments
Hello Guys,
Once Again I m back with My another Useful Article for You. In this Article I will describe you, how to auto select more than two select box. So, are U Ready??
Here is the Task that U have to achieve :-
You have three Select Boxes one for States, second for city and third for college.
What You want to Do :-
You want that if Some one selects State for Example :- Karnataka, the next drop down will automatically show u the lists of cities that comes Under Karnataka, Furthermore if you select Say Bangalore, the third drop down will show You the lists of colleges that comes under that city.
In short:-
STATE -> CITY -> COLLEGE
KARNATAKA -> BANGALORE -> IIT,Bangalore
Ruby on Rails with Ajax makes it very easy to achieve, It’s a 5 Step Process, Let’s See How
Step 1: create a new application, I am naming my application here ’sample’
Go to konsole/command Prompt:
: rails sample
This will create particular set of directories and files. Go into that Application
: cd /sample
Make a Model ‘State’
: ruby script/generate model State
This will create some files into your application, now open your migration file in your editor
i.e fever/db/migrate/001_create_states.rb
Type
: t.column :state, :string
and then save it.
open the model i.e state.rb in some editor
i.e fever/app/model/state.rb
Type
: has_many :cities
save this also, now Run
: rake db:migrate
This will migrate your states table in your database. To save your time I am generating scaffold here, go to konsole/command prompt and type
: ruby script/generate scaffold State
Note: this will create controller named states_controller.rb in your app/controllers directory.
Your first step is done, now we will proceed on 2nd step.
Step 2: create another model with the name city, for that type :
: ruby script/generate model City
This will create some files into your application, now open your second migration file in your editor
i.e fever/db/migrate/002_create_cities.rb
Type
: t.column :city, :string
t.column :state_id, :integer
save it.
open the model i.e city.rb in some editor
i.e fever/app/model/city.rb
Type
: belongs_to :state
has_many :colleges
save this and run
: rake db:migrate
This will migrate your cities table in your database. Create scaffold of this, Type
: ruby script/generate scaffold City
Note: this will create another controller named cities_controller.rb in your app/controllers directory.
Your Second step is done, now we will proceed on 3rd step.
Step 3: Create third model with the name college, for that type :
: ruby script/generate model College
This will create some files into your application, now open your Third migration file in your editor
i.e fever/db/migrate/003_create_colleges.rb
Type
: t.column :college, :string
t.column :city_id, :integer
save it.
open the model i.e college.rb in some editor
i.e fever/app/model/college.rb
Type
: belongs_to :city
save this and run
: rake db:migrate
This will migrate your colleges table in your database. Create scaffold of this, Type
: ruby script/generate scaffold College
Note: this will create another controller named colleges_controller.rb in your app/controllers directory.
You have done with your 3rd Step. Now we will move onto our fourth step
Step4: Create a Third Model with name = User, where we will display all the action, for that type :
: ruby script/generate model User
This will create some files into your application, now open your Fourth migration file in your editor
i.e fever/db/migrate/004_create_users.rb
Type
: t.column :firstname, :string
t.column :lastname, :integer
save it(I think two fields are more than enough to solve my purpose here).
Create a scaffold of this model
: ruby script/generate scaffold User
Note: that’s it. You have done with your basics steps, now we will use Ajax here, but before that I want you to insert some values of states, cities and colleges manually, be sure that you are giving right ’state_id’, and ‘city_id’ in your corresponding ‘cities’ and ‘colleges’ tables
Step 5: Open app/views/users/new.rhtml
and type below line between your head section
: <HEAD>
<%= javascript_include_tag “prototype” %>
</HEAD>
Open app/views/users/_form.rhtml, and type the below code after your firstname and lastname fields
: <p>State <br />
<% @states = State.find(:all) %>
<select name=”state_id” id=”state_id”>
<option value=”">Select City</option>
<% @states.each do |state| %>
<option value=”<%= state.id %>”>
<%= state.state %>
</option>
<% end %>
</select>
</p>
<p>City
<div id=”city_id_container”>
<select name=”city_id” disabled=”disabled”>
<option value=”">No City</option>
</select>
</div>
<%= observe_field(”state_id”, :frequency => 0.25, :update => “city_id_container”, :url => { :action => :add_link_city }, :with => “’state_id=’+value”) %>
</p>
Now open your users controller i.e app/controllers/users_controller.rb, and write the code as shown below
: def add_link_city
@cities = City.find_all_by_state_id(params["state_id"])
end
Now create a new file in app/views/users/add_link_city.rhtml, and add the code as shown
: <HTML>
<HEAD>
<%= javascript_include_tag “prototype” %>
</HEAD>
<BODY>
<p> <% @html = “<select id=’city_id’ name=’city_id’>” %>
<%= @html += “<option value=”>No City</option>” %>
<% @cities.each do |@cities| %>
<%= @html = “<option value=’#{@cities.id}’>#{@cities.city}</option>” %>
<% end %>
<%= @html = “</select>” %>
</p>
<p>College
<div id=”college_id_container”>
<select name=”college_id” disabled=”disabled”>
<option value=”">No College</option>
</select>
</div>
<%= observe_field(”city_id”, :frequency => 0.25, :update => “college_id_container”, :url => { :action => :add_link_college }, :with => “‘city_id=’+value”) %></p>
</BODY>
</HTML>
Go back again in your app/controllers/users_controller.rb, and add the method as shown below
: def add_link_college
@colleges = College.find_all_by_city_id(params["city_id"])
#@cities = City.find(:first, :conditions => ["city = ?", params[:city_id]])
end
Now create a new file in app/views/users/add_link_college and add the following code
: <HTML>
<HEAD>
<%= javascript_include_tag “prototype” %>
</HEAD>
<BODY>
<p> <% @html = “<select id=’college_id’ name=’college_id’>” %>
<%= @html += “<option value=”>No College</option>” %>
<% @colleges.each do |@colleges| %>
<%= @html = “<option value=’#{@colleges.id}’>#{@colleges.college} </option>” %>
<% end %>
<%= @html = “</select>” %>
</p>
<p> If Your College is not on the List, Please Click <%= link_to “Here”, :controller => ‘colleges’, :action => ‘new’, :id =>
@colleges.city_id %> here to Add Your College</p>
<p>Course
<div id=”course_id_container”>
<select name=”course_id” disabled=”disabled”>
<option value=”">No Course</option>
</select>
</div>
<%= observe_field(”college_id”, :frequency => 0.25, :update =>
“course_id_container”, :url => { :action => :add_link_course },
:with => “‘college_id=’+value”) %></p>
</BODY>
</HTML>
That’s It, You have done. Now you can check this in Your Browser. Type in Your url, http://localhost:3000/users/new, and see the magick.
Waiting for Your Valuable Responses.
Ruby on Rails for Beginners: How to Create Scaffold In Rails February 27, 2008
Posted by Puneet Pandey in Ruby On Rails.Tags: a simple example how to create scaffold on rails, basic scaffolding example, How to create scaffold in rails, rails for beginners, rails scaffold, ruby on rails scaffold, scaffolding using rails version 1.2
1 comment so far
Hello Guys this is My First, Post On Rails, Here I will Describe You how to create Scaffold on Rails. For those who are Unfamiliar with the Concept of Scaffold, Let me tell You A short Discussion about Scaffolding, Scaffolding is a basic Skeleton of your Application
For Example, if You want your HTML page will consist of Fist Name , Last Name, Email, Password, Address Etc. Scaffolding in rails will do that for you in few seconds, You don’t need to write Code for that.
Now, Let me Describe you, how scaffolding works..
Fist of all Check Your Rails Version, if You are Using Rails Version Greater than 1.2.5 you can’t create scaffolding in that, for that You Must have rails version 1.2.5
You can also take run two versions of rails at the same time.
To install rails Version 1.2.5 on your machine, type in the Konsole/Command Window :
for linux users : sudo gem install rails v=1.2.5
for windows users : gem install rails v=1.2.5
Now check your rails Version by Typing :
for both Linux/Windows User :rails -v
if your Konsole/Command Window shows this :
rails(2.0.2, 1.2.5)
means you have both rails version installed in your machine
in case if it shows this :
rails 1.2.5
you can install another version of rails by using following command :
for linux users : sudo gem install rails v=2.0.2
for windows users : gem install rails v=2.0.2
For those who are Installing rails first time on their machine, I recommand you to use both version of rails, to save extra work.
Now we have done with rails, the second step is to make an Application :
if you wish you can create you own folder where you can keep your all rails application
for me, I am Keeping all my rails applications on a Rails_Application folder
Now go to Konsole/command window..
Go to the directory where u want to keep your all rails application
(From here both Linux/Windows user follow these steps 
(this is my Directory)puneet@puneet-laptop:/home/windows1/Rails_Application$ rails sample
This Will create the following directories in sample folder
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create db
create doc
create lib
create lib/tasks
create log
create public/images
create public/javascripts
create public/stylesheets
create script/performance
create script/process
create test/fixtures
create test/functional
create test/integration
create test/mocks/development
create test/mocks/test
create test/unit
create vendor
create vendor/plugins
create tmp/sessions
create tmp/sockets
create tmp/cache
create tmp/pids
create Rakefile
create README
create app/controllers/application.rb
create app/helpers/application_helper.rb
create test/test_helper.rb
create config/database.yml
create config/routes.rb
create public/.htaccess
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/boot.rb
create config/environment.rb
create config/environments/production.rb
create config/environments/development.rb
create config/environments/test.rb
create script/about
create script/console
create script/destroy
create script/generate
create script/performance/benchmarker
create script/performance/profiler
create script/performance/request
create script/process/reaper
create script/process/spawner
create script/process/inspector
create script/runner
create script/server
create script/plugin
create public/dispatch.rb
create public/dispatch.cgi
create public/dispatch.fcgi
create public/404.html
create public/422.html
create public/500.html
create public/index.html
create public/favicon.ico
create public/robots.txt
create public/images/rails.png
create public/javascripts/prototype.js
create public/javascripts/effects.js
create public/javascripts/dragdrop.js
create public/javascripts/controls.js
create public/javascripts/application.js
create doc/README_FOR_APP
create log/server.log
create log/production.log
create log/development.log
create log/test.log
puneet@puneet-laptop:/home/windows1/Rails_Application$
Now go into your sample project by typing :
puneet@puneet-laptop:/home/windows1/Rails_Application$cd sample
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$
Now go into your database, here i m using MySql Database, and Create a new schema, named sample_development
You can also create a schema through konsole/command window by typing :
(for both Linux/Windows user) :
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$mysqladmin -u root create sample_development
this will create a new schema on your mysql database
Now the Important thing :
for those users who are using both rails version i.e(1.2.5, 2.0.2),
go to: sample/config/database.yml… and open that file
You will find the code like this :
# SQLite version 3.x
# gem install sqlite3-ruby (not necessary on OS X Leopard)
development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000
# Warning: The database defined as ‘test’ will be erased and
# re-generated from your development database when you run ‘rake’.
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
timeout: 5000
production:
adapter: sqlite3
database: db/production.sqlite3
timeout: 5000
Now follow the steps as I am doing, because this is the configuration code for mysql that support rails version 2.0.2 only, and you will not be able to create scaffold.
Follow this (for both Linux/Windows User) :
development:
adapter: mysql
database: sample_development
username: root(your mysql user name)
password: (Your Mysql Password)
socket: /var/run/mysqld/mysqld.sock
test:
adapter: mysql
database: sample_test
username: root(your mysql user name)
password: (Your Mysql Password)
socket: /var/run/mysqld/mysqld.sock
production:
adapter: mysql
database: sample_production
username: root(your mysql user name)
password: (Your Mysql Password)
socket: /var/run/mysqld/mysqld.sock
Now go into you sample/config/environment.rb and open it :
You Will See the following line of code written there :
RAILS_GEM_VERSION = ‘2.0.2′ unless defined? RAILS_GEM_VERSION
Replace this line with this:
RAILS_GEM_VERSION = ‘1.2.5′ unless defined? RAILS_GEM_VERSION
and at the bottom of the environemt.rb file which you have replaced the following code is also written:
config.action_controller.session = {
:session_key => ‘_myapp_session’,
:secret => ‘f088b01f77b99701afe5fb198ed40320c31df263a4d5885f9747f426a8b1d61170ffc3d69cfc617d3c637449b1bdf9ebcf0284e396ec22c84b99f2288f4b18c4′
}
Comment All this, or you can also remove those lines, but I recommend you to comment this. That’s all in environment.rb
Now go to app/contollers/application.rb and open it, you will find the code like this:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you’re not using the cookie session store
protect_from_forgery # :secret => ‘91fa0a704e62068793680a6a0b37d7cf’
end
Comment these two lines
#helper :all # include all helpers, all the time
#protect_from_forgery # :secret => ‘91fa0a704e62068793680a6a0b37d7cf’
To create a Scaffold, You Need to create a Model, Only After that you can create scaffold, there are some more way, but I am describing you the easiest way to do this.
Go into you command/konsole window, then go to your application directory:
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$
and then type:
ruby script/generate model User
this will create following files:
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/user.rb
create test/unit/user_test.rb
create test/fixtures/users.yml
create db/migrate
create db/migrate/001_create_users.rb
Now Open sample/db/001_create_users.rb, and add the following code:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :firstname, :string
t.column :lastname, :string
t.column :email, :string
t.column :password, :string
t.column :dob, :date
t.column :profile, :text
end
end
def self.down
drop_table :users
end
end
Note: before migrating your tables into your database, be sure that your database must contain a schema called sample_development.
If this schema doesn’t exist you can create manually on ur Mysql Server, or you can create manually by running this command:
mysqladmin -u root create sample_development
Now go into your rails application directory, through konsole/command window and type this:
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$ rake db:migrate
this command will migrate your following columns into your database, the o/p will look like this:
(in /home/windows1/Rails_Application/sample)
== CreateUsers: migrating =====================================================
– create_table(:users)
-> 0.0320s
== CreateUsers: migrated (0.0325s) ============================================
Now the Magic Comes, Type
puneet@puneet-laptop:/home/windows1/Rails_Application/sample$ ruby script/generate scaffold User
You Will See the following directories and files will create:
exists app/controllers/
exists app/helpers/
create app/views/users
exists app/views/layouts/
exists test/functional/
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
identical app/models/user.rb
identical test/unit/user_test.rb
identical test/fixtures/users.yml
create app/views/users/_form.rhtml
create app/views/users/list.rhtml
create app/views/users/show.rhtml
create app/views/users/new.rhtml
create app/views/users/edit.rhtml
create app/controllers/users_controller.rb
create test/functional/users_controller_test.rb
create app/helpers/users_helper.rb
create app/views/layouts/users.rhtml
create public/stylesheets/scaffold.css
That’s it, You have done it, Open your favourite browser, but don’t forget to start your mongrel/WeBrick Server by typing
sudo script/server
in the url type: http://localhost:3000/users/new
and see the rails magick.. isn’t it great!! the fields will also saved on each crate button.
Note: what is the problem in creating scaffold with rails v=2.0.2,
Solution: Each time when you type ruby script/generate scaffold User, All the files will be created, but the controller will not create, So Nothing will Work without a Controller. That’s why I write this post
Validates Username and Passowrd with PHP January 24, 2008
Posted by Puneet Pandey in PHP.Tags: assign user a session, how to validate a username and password in php, php script to validate username and password, simple php user validation script, validate user in php
5 comments
Hi Guys, Here I m Writing the code, How to Validates user name and password with the database…
If the username and Password matches with the database values we need to assign a session to that user..
for that here we are giving a simple session to a user.
<?PHP
session_start();
$server = “localhost”; //In case if u have some other write it here
$username = “Your Server Login Username”;
$password = “Your Server Login Password”;
$db_name = “Your Database Name”;
$db = mysql_connect($server, $username, $password) or die(”Connection to database failed, perhaps the service is down !!”);
mysql_select_db($db_name) or die(”Database name not available !!”);
Those Query Will Connect You with your Database…. Now I m Writing the Query..
$login = mysql_query(”select * from table_name where (username = ‘” . $_POST['username'] . “‘) and (password = ‘” . md5($_POST['password']) . “‘)”,$db);
Tip: here my table contains only Two Field user name and password, if ur table contains more that two fields you can also use *. There is no such issue of using (*) Specifically. (*) will select all the values from the database, where as I can also write
$login = mysql_query(”SELECT username, password FROM table_name WHERE (username = ‘” . $_POST['username'] . “‘) and (password = ‘” . md5($_POST['password']) . “‘)”,$db);
Note: Here first username you are watching is the name of the column in your database and the value $_POST['username'] is the value which we are getting from the form in the previous page. Similarly for password also.
Note2: md5($_POST['password']) is the Password which is stored in the database in the form encrypted value, so that no one can see what the password is!!
$rowcount = mysql_num_rows($login);
if ($rowcount == 1) {
$_SESSION['username'] = $_POST['username'];
header(”Location: welcomehome.php”);
}
else
{
header(”Location: login.php”);
}
?>
Note: here we are giving username and password to a variable called $rowcount.
Next if the user name and password matches with the database we are assigning user a session. and If user name and password doesn’t matches with the database we are redirecting the user back to the login page, else we will redirect the user to its home page.




