Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, 07 April 2010

The last week of looking at RoR:

  • Does all the plumbing if you follow the convention
  • Amazing how little code you need to write
  • The important stuff for CRUD apps is all there – validators, db relationships, CRUD functionality
  • The ORM works
  • Fast to develop!

In summary this look like a wonderful technology for putting together CRUD based business apps fast.

Shared hosting seems to be harder than .NET / PHP, however heroku.com is a great free resource.

Commercially speaking I think it would work very well in an enterprise where there is a need to develop apps fast (when isn’t there!) that do not require huge performance (I would argue that most apps I’ve worked on would be well suited in RoR).

| | # 

ruby script/generate scaffold flight departure:datetime arrival:datetime destination:string baggage_allowance:decimal capacity:integer

ruby script/generate scaffold seat flight_id:integer name:string baggage:decimal

rake db:migrate

image

 

image

What we want is a form that has the flight info on it, then the ability to add a new seat booking.

Partials

Coppied seat/new.html.erb  into flight/show.html.erb file rendering as a partial

_new_seat.html.erb

Changed:

<% form_for(seat) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :flight_id %><br />
    <%= f.text_field :flight_id %>
  </p>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :baggage %><br />
    <%= f.text_field :baggage %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

the form_for(@seat) to (seat) to become a local variable to the partial.  This is good practise.

called the partial from flights/show.html.erb as

<%= render :partial=>"new_seat", :locals=>{:seat=>Seat.new(:flight_id=>@flight.id)}%>

<% form_for(seat) do |f| %>
  <%= f.error_messages %>
  <%= f.hidden_field :flight_id %>

image

We also need a partial for the seat list

image

however this is bad as its displaying the seats for all flights

Connect the models together

means we don’t need to use finders.. it works automatically.

class Flight < ActiveRecord::Base
  has_many :seats
end

then when rendering out the listing of seats we can pass in the array  in show.html.erb

<%= render :partial=>"seat_list", :locals=>{:seats=> @flight.seats}%>

in the model:

belongs_to :flight
    def validate
        if baggage > Flight.find(flight_id).baggage_allowance
            errors.add_to_base("You have too much baggage")
        end
        if flight.seats.size >= flight.capacity
            errors.add_to_base("The flight is fully booked")
        end
    end

image

another custom validator in the seat model

if flight.seats.size >= flight.capacity
            errors.add_to_base("The flight is fully booked")
        end

image

**TO DO put in a validator that checks there is a number for baggage

| | # 

ruby script/generate scaffold client_workout client_name:string trainer:string duration_mins:integer date_of_workout:date paid_amount:decimal

rake db:migrate

Problem is that the scaffolding app doesn’t do exactly what we want.

image

what we want is just the listing for Lenny Goldberg ie a filter.

Creating a Form with no Model

instead of form_for

<% form_for(@ad,:url=>{:action=>'update'}) do |f| %>
  <p><b>Name</b><br /><%= f.text_field :name %></p>
  <p><b>Description</b><br /><%= f.text_area :description %></p>
  <p><b>Price</b><br /><%= f.text_field :price %></p>
  <p><b>Seller</b><br /><%= f.text_field :seller_id %></p>
  <p><b>Email</b><br /><%= f.text_field :email %></p>
  <p><b>Img url</b><br /><%= f.text_field :img_url %></p>
  <p><%= f.submit "Update" %></p>
<% end %>

we use form_tag

<% form_tag "/client_workouts/find" do%>
      <%= text_field_tag :search_string%>
      <%= submit_tag "Search" %>
    <% end %>

 

image

image

by putting in dave into the search box, we can see it coming through in the controller by using puts to output to the console.

So we only need those records where client_name = the search string.

def find
      puts params[:search_string]
      @client_workouts = ClientWorkout.find_all_by_client_name(params[:search_string])
  end

The framework creates finders for each attribute.. eg find_all_by_client_name.

and I just wired up to a find.html.erb file.

image

however we want to search on trainer as well ie where client_name=”Lenny Goldbery” or trainer = “Lenny Goldberg”

@client_workouts = ClientWorkout.find(:all, :conditions=>["client_name = ? OR trainer = ?",
                          params[:search_string], params[:search_string]])

image

The crowd goes wild!  Can filter on client_name or trainer.

Validators

A number:

class ClientWorkout < ActiveRecord::Base
    validates_numericality_of :paid_amount
end

Mandatory:

class ClientWorkout < ActiveRecord::Base
    validates_numericality_of :paid_amount
    validates_presence_of :trainer
    validates_presence_of :client_name
end

image

 

Doing it on custom code:

class Ad < ActiveRecord::Base
  validates_presence_of :price
  validates_presence_of :name
end

def create
      @ad = Ad.new(params[:ad])
      if @ad.save
        redirect_to "/ads/#{@ad.id}"
      else
        render :template => "ads/new"
      end
  end

<% form_for(@ad,:url=>{:action=>'create'}) do |f| %>
    <%=f.error_messages%>

image

| | # 

here is how we do it from scaffolding:

Symbols and Strings

<%= f.label :seat_id_seq %>   This is a symbol.  They always start with a colon.  Generally used to name things.  Mostly interchangeable with strings.

<%= f.label “Seat #” %>   This is a string.

Add a column to the DB

to add the database we:

ruby script/generate scaffold ticket name:string seat_id_seq:string address:text price_paid:decimal email_address:string

to add a row:

ruby script/generate migration AddPhoneToTickets phone:string

important bit is Add…To…

then

rake db:migrate

image

then changed the 4 view to display the new field.

Starting From Scratch

The scaffolding can create too much code!  Here is an app just generating 1 page to start with (a show page)

ruby script/generate model ad name:string description:text price:decimal seller_id:integer email:string img_url:string

models have singular names eg ticket, ad

Controller

ruby script/generate controller ads

controllers have plural names

Routes

map.connect '/ads/:id', :controller=>'ads', :action=>'show'

use the ads_controller.rb, and the show template.

View

show.html.erb

<p>
    <b>Name:</b><%= @ad.name %>
</p>

image

Index Page

controller:

  def index
    @ads = Ad.find(:all)
  end

index.html.erb

<% for ad in @ads%>
    <li><a href="/ads/<%= ad.id%>"><%=ad.name%></a></li>
<% end %>

route

map.connect 'ads/', :controller=>'ads', :action=>'index'

image

Layouts

images into public/images

stylesheet into public/stylesheets

apps/views/layouts/ads.html.erb

image

Post New Ads Online

routes

map.connect 'ads/new', :controller=>'ads', :action=>'new'
map.connect 'ads/create', :controller=>'ads', :action=>'create'

viewff

 

ads/new.html.erb

and the form will be submitted to:

ads/create

 

RoR Text Editor

Am trying http://www.e-texteditor.com/

ctrl shift p – toggle between project view and editor view

http://www.e-texteditor.com/wiki/index.php/Projects#Keyboard_navigation – keyboard shortcuts

Create Form Helper

Rails can create forms that are associated with model objects. so in new.html.erb

<% form_for(@ad,:url=>{:action=>'create'}) do |f| %>
  <p><b>Name</b><br /><%= f.text_field :name %></p>
  <p><b>Description</b><br /><%= f.text_area :description %></p>
  <p><b>Price</b><br /><%= f.text_field :price %></p>
  <p><b>Seller</b><br /><%= f.text_field :seller_id %></p>
  <p><b>Email</b><br /><%= f.text_field :email %></p>
  <p><b>Img url</b><br /><%= f.text_field :img_url %></p>
  <p><%= f.submit "Create" %></p>
<% end %>

eg this comes out as:

<b>Name</b><br /><input id="ad_name" name="ad[name]" size="30" type="text" />
image 

so when the submit button is pressed, this routes back to the create action in the AdsController.

Controller

def new
      @ad = Ad.new   
  end


  def create
      @ad = Ad.new(params[:ad])
      @ad.save
      redirect_to "/ads/#{@ad.id}"
  end

note:  create an empty ad object before passing onto new

and we have an automatic redirect to the listing

otherwise could have commented out and it would go automatically to create.html.erb:

image

Edit a Record

routes add in

map.connect 'ads/:id/edit', :controller=>'ads', :action=>'edit'
map.connect 'ads/:id/update', :controller=>'ads', :action=>'update'

controller add in

def edit
      @ad = Ad.find(params[:id])
  end
  def update
      @ad = Ad.find(params[:id])
      @ad.update_attributes(params[:ad])
      redirect_to"/ads/#{@ad.id}"
  end

view add in

<% form_for(@ad,:url=>{:action=>'update'}) do |f| %>
  <p><b>Name</b><br /><%= f.text_field :name %></p>
  <p><b>Description</b><br /><%= f.text_area :description %></p>
  <p><b>Price</b><br /><%= f.text_field :price %></p>
  <p><b>Seller</b><br /><%= f.text_field :seller_id %></p>
  <p><b>Email</b><br /><%= f.text_field :email %></p>
  <p><b>Img url</b><br /><%= f.text_field :img_url %></p>
  <p><%= f.submit "Update" %></p>
<% end %>

Security

in the AdsController

before_filter :check_logged_in, :only => [:edit, :update]

  private
    def check_logged_in
        authenticate_or_request_with_http_basic("Ads") do |username, password|
            username == "admin" && password == "secret"
        end
    end

image

 

Delete

image

Just calling a single action on the controller called destory which then redirects back to index.

 

**TODO put this live

| | # 
# Thursday, 01 April 2010

elevator

use cases

paper prototype:

put mock up live

http://pubtricks.heroku.com/

image

changes to scaffold:

background colour in all games in \views\layouts\games.html.erb

| | # 
# Wednesday, 31 March 2010

 

heroku - free
dreamhost - 9us per month
railsplayground - 5us per month
slicehost - vps.. bout 20 per month

gem install heroku

image

create git repo

heroku create

  it then added ssh key to remote

git remote – has added in the remote

git push heroku master

image

hmmm…

tried:  heroku keys:add c:\id_rsa.pub

remembered i’d put my key in

c:\home\.ssh\id_rsa.pub

heroku rake db:migrate

image

The crowd goes wild!

| | # 
# Friday, 26 March 2010

After an awesome mountainbike ride I’ve managed to break my collar bone.  I wouldn’t recommend this :-)

So I though I’d make the most of the ‘opportunity’ and have a look at RoR..

image

Goal:  To deploy an application live

Downloading RoR

rubyonrail.org – download.  Getting 1.8.7 of Ruby.. tick add to executable, and associate .rb

rubygems – package manager..extract, run setup.rb

gem install rails 2.3.5

rails --version

http://docs.heroku.com/windows – good install screencast

Hello World App

rails blog

cd blog

ruby script/server

localhost:3000

uses WEBrick 1.3.1

am getting strange error:

image

Install SQLite3

http://akitaonrails.com/2009/01/13/the-best-environment-for-rails-on-windows

http://www.sqlite.org/download.html

sqlite3.exe into \windows

sqlite3.dll into system32

 

http://allaboutruby.wordpress.com/2009/07/20/installing-rails-on-windows-3-years-later/

gem install sqlite3-ruby

cd \code\ruby\hello

ruby script\server

the crowd goes wild!!!

image

ruby script/generate scaffold post title:string description:text

This command creates a Post scaffold, a model/controller/view ready to be updated.  The post model will have 2 fields – a title which is a single line of text and a description, which is multi-line text.

image

Run the database migration. This is because after creating the scaffold, the database is not automatically updated with the new blog model, you need to do it manually by running a rake db:migrate command

image

cool – now have db integration and working scaffold

http://railsforum.com/

http://railscasts.com/episodes/archive

http://allaboutruby.wordpress.com/2009/08/08/5-minute-project-in-rails/ – very simple app.

http://ruby-toolbox.com/categories/rails_form_builders.html

 

http://guides.rubyonrails.org/getting_started.html#installing-rails

in c:\code

rails blog   - this creates a rails app that uses sqllite.

 

The Blog from Guide

http://guides.rubyonrails.org/getting_started.html

rails blog

rake db:create

rake –T  shows all rake (general purpose command runner) commands

ruby script/generate controller home index  -creates files including app/views/home/index.html.erb. This is the template that will be used to display the results of the:

 index action (method) in the home controller.

image

edit index.html.erb to <H1>Hello Rails</H1>

ruby script\server

http://locahost:3000/home/index

image

Change home page

config\routes.rb

map.root :controller => "home"

Scaffolding

Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

ruby script/generate scaffold Post name:string title:string content:text

This creates a model, a db migration ruby file, views and changes the config\route.rb file.

rake db:migrate

put in:  <%= link_to "My Blog", posts_path %>

image

then

image

image

 

Validation

The model file, app/models/post.rb is about as simple as it can get:

validates_presence_of :name, :title

validates_length_of :title, :minimum => 5

image 

View

<% @posts.each do |post| %>
  <tr>
    <td><%=h post.name %></td>
    <td><%=h post.title %></td>
    <td><%=h post.content %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_post_path(post) %></td>
    <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>

h is a rails helper

lik_to buils hyperlinks

edit_post_path

new_post_path

Layout

These are containers for views

app\views\layouts\posts.html.erb

<body style="background: #EEEEEE;">

now all views for posts have a grey background

Entering Data and Wiring Up

<% form_for(@post) do |f| %>
  <%= f.error_messages %>

form_for block is used to create an html form..

<%= f.label :name %><br />

<%= f.text_field :name %>

wires up a text box with name attribute

DRYing up Code - Partials

scaffold generated views for new and edit are largely identical.. so can use partials template.

_form.html.erb  underscore is convention for partial

<% form_for(@post) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </p>
  <p>
    <%= f.submit 'Save' %>
  </p>
<% end %>

and in new.html.erb

<h1>New post</h1>

<%= render :partial => "form"  %>

<%= link_to 'Back', posts_path %>

****7.2 Using Filters to eliminate controller duplication

 http://wiki.devchix.com/index.php?title=Server_2003

The Blog App Video

From front page of rails site:

http://www.opensourcerails.com/

http://www.softwaredeveloper.com/features/best-ruby-on-rails-061307/

http://www.3months.com/technology

http://blog.obiefernandez.com/content/

 

Auth

http://wiki.rubyonrails.org/howtos/authentication-authorization

Authentication is what you do when you let a user identify itself. This is needed when you want to offer a login access to your application.

Authorization is what you do when you check the credentials of a user before letting him/her interact with specific sections of your system. This is needed when you have restricted areas/actions.

| | #