Meon Love Meehon

Entries categorized as ‘Ruby on Rails’

Ruby on Rails Wiki

April 23, 2009 · 2 Comments

Install Ruby/Rails for your particular platform, and make sure you have SQLite installed (this comes with a Mac if you have a Mac). Installation wiki pages can be found here: MacWindowsLinux.

  1. Run the Rails command line tool to create the application. 

    $ rails myapp

    This will create the skeleton of your Rails app.

  2. Go into your directory, probably by typing: 

    $ cd myapp
  3. Startup your Rails server by running: 

    $ ruby script/server

    Note: You may not need the “ruby” part of that if you’re on a Mac or Linux.

  4. Call up a browser and go to http://localhost:3000. You should see that Rails is running; that’s all there is to it! Pat yourself on the back, you deserve it.

  1. Open the application in your editor of choice.
  2. Open the config/database.yml file. This is where you would typically configure different databases for your application, but for the sake of this example you shouldn’t have to touch anything. The default database names, as you may have noticed, are taken from the name of your Rails app.
  3. Open up another command prompt (that way we can keep the server running in the background), and in your application directory run: 

    $ rake db:create

    This will create your development database.

  4. Now we want to create our first table and interface. In Rails, this typically means we’re going to create a scaffoldto start from. A scaffold is simply a starting point, and we can add increasingly complex code from there. Let’s first run the scaffold command without any parameters: 

    $ ruby script/generate scaffold

    Take a look at the output generated. It shows you how to use the command.

  5. Now let’s go ahead and use scaffold to start generating our web application. We’re going to create a users table: 

    $ ruby script/generate scaffold user first_name:string last_name:string active:boolean

    It’s okay if you copy and paste this code, I won’t tell anyone. So now your scaffold is created, which is just a bunch of template files.

  6. Let’s run the migration it created for us (to create the database table). 

    $ rake db:migrate
  7. Now go back to your browser (start your server back up if you killed it), and go to http://localhost:3000/users
  8. Create a few users, and play around with your Rails interface!

  1. We just realized that we forgot to add a bio field for a user – oops! We could either create a new migration to add that column, or roll back the migration that was created for us. Let’s do the latter. To remove the table so we can add a column, run this command: 

    $ rake db:rollback

    This will roll back one migration.

  2. Now open the migration located in the /db/migrations/ directory. It should be the only file.
  3. Notice how the migration has an up method to migrate up, and down method to migrate down.
  4. We want to add that bio field, so after the t.boolean :active line, add: 

    t.text :bio
  5. Save the file, and run rake db:migrate again to migrate your database up: 

    $ rake db:migrate
  6. If you checked your browser at this point, you’d notice that the bio field isn’t automatically showing up in our user’s information or forms. We will need to add this ourselves. Yes, we could have erased the files and run the scaffold command to get this field, but then you wouldn’t learn anything.
  7. Lets open up the /app/views/users/new.html.erb file. This is what renders our New User form. We need to add a bio field using the following code below the active checkbox. 

    <p>
      <%= f.label :bio %><br />
      <%= f.text_area :bio %>
    </p>
  8. Now open up the New User page in your browser http://localhost:3000/users/new. You should see the bio field, and be able to add new users with a bio.  For extra credit, you could use the same code if you wanted to update the edit view (in /app/views/users/edit.html.erb) so you can edit a user’s bio.
  9. When you create a user, you’re brought automatically to his/her show page. Let’s add the bio to the show page. You can do this by opening the /app/views/users/show.html.erb file, and underneath the Active field, adding: 

    <p>
      <b>Bio:</b>
      <%=h @user.bio %>
    </p>
  10. Save the file and check it out in the browser. If you don’t see your change at first, make sure you are on the showpage (and not the index). When you get to this part, let out a barbaric “woot!”, you’ve made some great progress.

  1. In Rails, we put our validations in our model files, so let’s open /app/models/user.rb.
  2. We want to require that a user enter their first name and last name, so let’s add validation to our User model, so it ends up looking like this: 

    class User < ActiveRecord::Base
      validates_presence_of :first_name, :last_name
    end
  3. Save the file, go to your browser, and attempt to create a user without a first name or last name.
  4. Rails has many helper validation classes, and you can see a list on the right side of this API page.

 For extra credit, add another validation to your app just for fun.

  1. If you viewed the browser HTML source of your application, you may have noticed that your application is in some sort of layout. By default, when you ran the scaffold command, a /app/views/layouts/users.html.erb file was created, and used as your layout.
  2. You’ll probably only want to use one layout for most of your controllers, so let’s give this a more generic name. Rename users.html.erb to application.html.erb. As a Rails convention, now that you have anapplication.html.erb file in your layouts directory, all controllers will use this by default (you can override this later if you want).
  3. Let’s add something to our layout just for fun. Open up the application.html.erb and add something like: 

    <h2>Rails Rocks!</h2>
  4. Save the file, go to your browser, and you should see the change you made reflected on ALL pages of the website.

  1. Let’s have some fun playing with our User Model. In your command prompt, type: 

    $ ruby script/console

    You are now in a Ruby IRB session which has access to your models.

  2. Before we start playing, run the following command so that we can see what SQL commands are going to be generated for us. 

    $ ActiveRecord::Base.logger = Logger.new(STDOUT)
  3. Let’s try a simple Ruby statement to make sure everything is working: 

    puts "Hello Dude!"
  4. Now let’s try having some fun with our model. Create a new model by doing something like this: 

    u = User.new
    u.first_name = "Gregg"
    u.last_name = "Pollack"
    u.save

    Notice the SQL that is generated.

  5. Now try doing it all in a single line: 

    User.create(:first_name => "Joe", :last_name => "Blow")

    If you hit any errors, check for syntax problems.

  6. Let’s fetch the user with first name of Joe, and change his last name to “Johnson”. 

    u = User.find_by_first_name("Joe")
    u.last_name = "Johnson"
    u.save

    Notice the SQL that gets generated; nice!

  7. Now let’s delete the user. 

    u.destroy
  8. Have some fun trying the following commands to see what they do: 

    User.first
    User.last
    User.all

    Feel free to set a variable with the values, and play around with changing attributes. Do note that .all returns an array, so you may want to use [0] or [2] to refer to a particular item in the array.

  9. Let’s print out all the users in your system in upper case: 

    User.all.each {|user| puts user.first_name.upcase }
  10. You’ll notice that it prints out the first names, and then it also returns the array of Users. Remember, every method in Ruby returns something, even if it’s nil.
  11. Let’s create an array of all of the last names in our system: 

    User.all.map {|user| user.last_name }

    What we’re interested in here is the return value, which should be an array of last names.

  12. Take a look at the API page here. Along the right you’ll see all of the methods you can run on ActiveRecord objects. Try a few.

Categories: Ruby on Rails

Rails on Vista

April 23, 2009 · Leave a Comment

If you are like me, you usually develop RoR applications on linux (I am talking about non-mac people, anyway…).  My setup is usually looks like this : XUbuntu + Netbeans  + Mysql/Sqlite3 + Apache + Phusion Passanger.  Assuming you got all your development done andi it’s called  “MyApp”.

On Windows 2008 Box

Step 1:  Install Ruby, gems and rails

Get Ruby 1.8.6 One-Click Installer (from http://www.ruby-lang.org/en/downloads/) and make sure to install gems.

Then installing rails is a breeze. Open a command line window and type

gem install rails –include-dependencies

Step 2: Install mongrel & mongrel_service

gem install mongrel
gem install mongrel_service

Step 3 : Install Apache and enable required modules

A. Get Latest msi version for windows (currently apache_2.2.10-win32-x86-no_ssl.msi) from http://httpd.apache.org/download.cgi

B. Install as a service.

C. Enable required modules by uncommenting these following line in http.conf file (which can be found at C:Program Files (x86)Apache Software FoundationApache2.2conf

if you followed the default installation)

LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so

D. Start the server to makesure it starts and runs OK. If there is a problem with config file you would see an error.

Step 4 : Install database drivers

This really depends on your database. Remember that for sqlite3, if you are having trouble installing latest

drivers, try giving a version no as follows.

gem install –version 1.2.3 sqlite3-ruby

Step 5 : Create a skeleton rails application

I am assuming we are keeping our rails application in C:railsapps

So create the new rails application by changing to that directory and running

rails Myapp

The reason for creating a skeleton instead of just copying our application from Linux, is that the way some files are created on windows may not be same as linux.  So let it create a dummy app and test it to make sure, its able to pullup the welcome page.

Step 6 : Copy your application Files over to windows

The directories usually copy are

app/      all directories below
public/   any static files you created,  directories  stylesheets, javascripts and images.
config/   routes.rb, database.yml
db/        schema.rb

(Again, this is highly dependent on your application. May be you didn’t have any custom javascripts or stylesheets in that case you could skip public/ folder all together)

Step 7:  Load Database Schema into production db

rake db:schema:load RAILS_ENV=production

Step 8 : Create Multiple Mongrel Server Instances and start them as automatic

I am creating 3 instances here

mongrel_rails service::install -N mongrel_Myapp1 -p 3001 -e production -c c:railsappsMyapp
mongrel_rails service::install -N mongrel_Myapp2 -p 3002 -e production -c c:railsappsMyapp
mongrel_rails service::install -N mongrel_Myapp3 -p 3003 -e production -c c:railsappsMyapp

which creates three services (you could see them Start>>Administrative Tools >> Services Panel). By default the services are created as  “Startup Type — Manual”. Set that to “Automatic” so that they will start back again if you reboot the server.

Step 9: Setup Apache

In the apache’s http.conf file make sure to have these following lines

# Virtual hosts
Include conf/extra/httpd-vhosts.conf

Then make your  conf/extra/httpd-vhosts.conf  File look like this

#——- Start of http-vhosts.conf file ———————————–

NameVirtualHost *:80
#Proxy balancer section (create one for each ruby app cluster)
<Proxy balancer://Myapp_cluster>
BalancerMember http://127.0.0.1:3001
BalancerMember http://127.0.0.1:3002
BalancerMember http://127.0.0.1:3003
</Proxy>
<VirtualHost *:80>
DocumentRoot “C:/railsapps/Myapp/public”
ErrorLog “logs/Myapp-error.log”
CustomLog “logs/Myapp-access.log” common
<Directory C:/railsapps/Myapp/public/ >
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
RewriteEngine On
# Rewrite index to check for static files
RewriteRule ^/$ /index.html [QSA]
# Rewrite to check for Rails cached pages
RewriteRule ^([^.]+)$ $1.html [QSA]
# Redirect all non-static requests to cluster
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ balancer://Myapp_cluster%{REQUEST_URI} [P,QSA,L]
</VirtualHost>
#——- End of http-vhosts.conf file ———————————–

If you ever used apache’s mod_rewrite module then you dont need any explanation. If you don’t, then breif explanation wont make much sense to you either….

Becareful with name of Proxy balancer and make sure to use exact name in last RewriteRule (in the above case its Myapp_cluster), then you should be fine.

Step 10 :  Start the mongrel services and Restart Apache.

Now when you go to http://localhost/  you should be sent to one of the 3 servers of balancer and see the application.  If you see broken images or ugly layout, then it means you didnt copy my “http-vhosts.conf” file properly!  Have a careful look at <Directory> directive again. You would know.

Happy programming and happy holidays.  Ciao.

p.s.  If you want to run multiple rails applications on same server like MyApp1, MyApp2…., have a look at rails.conf I used in “Fedora production setup“. By adding another balancer and modifing RewriteRules littlebit, its not that tough.

 

 

Here is a quick add-on – How to set up a mongrel service to proxy from Apache!

First, you need the mongrel_rails gem, so install that using

gem install mongrel_rails

If we are creating a blog application, we want to set it up so that the URL we visit ishttp://blog/, so you need to open your hosts file, which can be found in C:\WINDOWS\system32\drivers\etc\, and enter the following line:

127.0.0.1 blog

Then you need to open your Apache config. Where you setup virtual hosts, enter this:

 

ServerName blog
ServerAlias *.blog

DocumentRoot C:/root/to/your/rails/app's/public/directory

RewriteEngine On

# Redirect all non-static requests to Mongrel
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$http://127.0.0.1:7000%{REQUEST_URI} [P,QSA,L]

# Custom log file locations
ErrorLog C:/root/to/your/rails/app/logfiles
CustomLog C:/root/to/your/rails/app/logfiles combined

 

Lastly, go into your command line. Navigate to your rails directory and run this command:

mongrel_rails service::install -p 7000 -N MyRailsApp

This will install the service. Restart Apache, and run:

net start MyRailsApp

And you should have a fully working proxy to mongrel!

Categories: Ruby on Rails