Creating a Website using Ruby On Rails [Basics]
PDF Version
Web Programming Project=> E-Commerce Website built on Rails
Tools
I recommend Instant Rails for executing Rails on Windows. Download and extract the folder from here.
Initialization
- Start up InstantRails.exe
- Start up the Apache and MySQL
- Start up the Ruby Console Window
Creating a Rails Application
rails app_name
Creating a Database and tables
ruby script/generate model table_name column_name:type ...
eg:- ruby script/generate model user first_name:string last_name:string password:string username:string
After creating all the tables that you need, you need to import them to the database with the following command.
rake db:migrate
Now you would be able to see a development.sqlite3 file in your \rails_apps\app_name\db folder.
You can view the database using the SQLite Manager (Available as an add-on for Mozilla Firefox. You can get it here.
Now you would be able to see a development.sqlite3 file in your \rails_apps\app_name\db folder.
You can view the database using the SQLite Manager (Available as an add-on for Mozilla Firefox. You can get it here.
Creating a Controller
Now that we have all our tables in place, we need a controller for the app. You can do this by typing in the following in the console.
ruby script/generate controller controller_names
The controller name should be in plural.
Editing the routes.rb
You can start creating your pages in the app_name/app/views/controller_name folder under the name :- file_name.html.erb, but before you do that its necessary that you configure a file called routes.rb
routes.rb is file you can find in the app_name/config folder
This file decides which page opens up on entry of each URL. It also decides the controller that is supposed to be used in the page and the ruby function to go along with it.
Suppose on entry of the URL "/app_name/" on your browser, you want the index.html.erb to be opened up.
For that you add the following entry in the file:-
map.connect '/app_name/', :controller=>'controller_name', :action=>'file_name'
Most of the time the action for the particular page is given the same name as the page. You define the action in the controller file which is app_name/app/controller/controller_name_controller.rb
Running your App
In your InstantRails open Apace>Rails Applications>Manage Rails Applications...
Check the checkbox of your app and select "Start with Mongrel"
Now go to your browser and type in the URL:- "localhost:3000/app_name/". Given the fact that you have already defined which file to open in case of the URL '/app_name/' in your routes.rb, the particular file you have defined would open up!
Basic Actions you can Perform
Inserting data into a TABLE
Most functions similar like Insert, Delete and Update are made possible using 2 different pages much like pHp. Suppose you initial page containing your form data is ==> /app_name/form
Make a file form.html.erb in your views folder much like the index page I mentioned earlier.
Define in your routes.rb:-
map.connect '/app_name/form', :controller=>'controller_name', :action=>'form'
Now since this page doesn't have any action to perform, you can skip mentioning it in the controller file, or just leave something like,
def form
end
def form
end
Now we have to configure the form.html.erb file so that we can accept input.
Now it's easier to demonstrate this with an example. Suppose we are making up a page so that a user can signup. Our table has columns for username, password and the name of the person.
We first define the form tag for Ruby in the file. Most ruby based tags are written as <%= %> though certain codes are written in <% %> and are called scriptlets.
The ruby equivalent to
<form action="/app_name/confirmation">
Name: <input type="text" name="name">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Re Enter Password: <input type="password" name="repassword">
<input type="submit">
</form>
is
<% form_tag "/app_name/confirmation" do %>
Name: <%= text_field_tag :name %>
Username: <%= text_field_tag :username %>
Password: <%= password_field_tag :password %>
Re Enter Password: <%= password_field_tag :repassword %>
<%= submit_tag "Sign Up" %>
<% end %>
Now the information has to be processed and saved.
As mentioned above the page is redirected to 'app_name/confirmation'
define that in the routes.rb file
map.connect '/app_name/confirmation', :controller=>'controller_name', :action=>'confirmation'
Any parameter received from a form can be accessed by params[:parameter_name]
Now if our tables name is "user" and the column names are firstname, password and username
In the controller file now write
def confirmation
@user = User.new #making a new variable element "@user" for the table "user"
if(params[:password] == params[:repassword]) #checks if both parameters passed as password are the same
@user.firstname = params[:name] #copying parameters to the Table variable.
@user.password = params[:password]
@user.username = params[:username]
@user.save #saving the table variable in the database.
end
end
Selecting Values from a table
To search the table and retrieve values we can use 2 methods. If all you want is to find the tuples of elements with a particular entity in a single column, then use
@var = Table.find_all_by_column_name
the result would be stored in @var which is an array. Which you can access by @var[0], @var[1] ... etc
On the other hand if you want to execute a query which is more complex then use:
@var = Table.find(:all, :conditions=>['column_1 = ? and column_2 = ?', value_1, value_2]
this is similar to the SQL query,
SELECT * FROM TABLE WHERE COLUMN_1 = VALUE_1 AND COLUMN_2 = VALUE_2
Both these methods return the results as an array which you can access by @var[0], @var[1].. etc
Updating Stuff in your Table
By default any table you create has an id column in it.
Suppose that you need to amend an object in your table relating to a particular id. If /app_name/id/edit has to provide an option to edit the particular tuple with the given id..
First edit your routes.rb and add..
maps.connect '/app_name/:id/edit', :controller=>'controller_name', :action=>'edit'
Also remember to make an edit.html.erb to store the form which should provide the necessary changes.
In the controller, the action provides the particular tuple to the edit page.
def edit
@user = Table.find(params[:id]) #Using find makes search in id column by default
end
Now @var is available to be used within 'edit.html.erb'
The form in edit.html.erb is a little different from what we've seen before since we use the actual table object to make the form here.
<% form_for(@user, :url=>{:action=>'update'}) do |f| %> <!-- The action here redirects to a page called update, thus effectively redirecting to /app_name/id/update . here 'f' is the object for @ad -->
Name: <%= f.text_field :username %>
Password: <%= f.password_field :password %>
Username: <%= f.text_field :name %>
<%= f.submit "Update" %>
Now create the update entry in routes.rb
maps.connect '/app_name/:id/update', :controller=>'controller_name', :action=>'update'
In controller write the following code to update the entry
def update
@user = Table.find(params[:id]) #Takes the tuple with given id
@user.update_attributes(params[:ad]) #updates the tuple with the ad object passed from the edit page
redirect_to "/app_name/" #used to redirect to a particular page
end
Another way to update is by using the following command...
Table_name.update(row_id, :column_name=>value, column_name=>value2)
Deleting values from a TABLE
To delete any value from a particular table, say via an id passed from a page, Make the necessary route entries and form necessary to find the object to be deleted. then
def delete
@ad = ....... #code to select the tuple that needs to be deleted
@ad.destroy
end
Form Validation
The form validation in rails is done inside the model. For this you initially have to open up:
/app_name/app/models/table_name.rb
Here the table name refers to the table for which you are going to conduct the validation.
It might look something like the following..
class Table_Name < ActiveRecord::Base
end
There are a lot of validation functions... For checking the presence of a particular column in the input, we add,
class Table_Name < ActiveRecord::Base
validates_presence_of :column_name
end
Few other methods
validates_numericality_of :column_name
validates_length_of :column_name :maximum=>length #to check length. replace length with number
validates_format_of :column_name :with=>/regular expression/ #for stuff like email validation Visit this link for more information
validates_uniqueness_of :column_name
If any of the validation fails, then the return value for @ad.save would be false. You can use this to redirect your form accordingly.
In the controller..
if ( @var.save )
In the controller..
if ( @var.save )
#successful
else
#error
end
else
#error
end
Adding CSS and Javascript to your Webpage
Adding CSS to your webpage is a little different from what you do normally. All you need to do is add the following script in your page
<%= stylesheet_link_tag "stylesheet_name.css" %>
Now add your style sheet to /app_name/public/stylesheets
As for java script, add
<%= javascript_include_tag "jscript_name.js" %>
And now add your java script to /app_name/public/javascripts
As for java script, add
<%= javascript_include_tag "jscript_name.js" %>
And now add your java script to /app_name/public/javascripts
Other Stuff
Authentication
Following are a few other things worth mentioning. To make functions work on admin authorization only, you can add the following code within your controller
class ControllerNameController <ApplicationController #should be already in a default controller file
before_filter :check_logged_in, :only => [:def1, :def2, ...] #provide the definitions that should be protected as def1, def2 ...etc
.......
....... #Your definitions/actions
private
def_checked_login #Filter calls this method if someone tries calling the given definitions
authenticate_or_request_with_http_basic("Table_Name") do |username,password| #Secured Tables Nme
username == "your_username" && password == "your_password" #Username or password necessary for login
end
end
end
Session
If you want to maintain a particular variable throughout different pages without passing the variable to the page every single time, you can use a session
def action_name
.....
.....
session[:variable_name] = ...
end
This makes the variable available in other pages when they are loaded without passing it each time.
[WILL BE UPDATED]