Ruby on Rails之InstantRails使用

來源:互聯網
上載者:User

下面我們開始 學習 Ruby On Rails (ROR)入門教程
第一我們首先是 快速配置 Ruby On Rails 的開發環境
1. 下載 InstantRails-2.0-win.zip
可以到官方下載,http://rubyforge.org/frs/?group_id=904
也可以到 /download/tools/InstantRails-2.0-win.zip 改為
/download/tools/InstantRails-2.0-win.7z 下載
2. 下載好後, 就解壓
如果從 /download/tools/InstantRails-2.0-win.7z 下載
需要輸入解壓密碼: www.17rumen.com
檔案比較多, 稍等, 軟體不用安裝, 解壓就可以用。
建議新手使用 InstantRails 作為 ROR 的入門開發環境。
InstantRails.exe 運行
看到 Apache MySQL 顯示 綠色的燈, 表明正常運行

 

http://localhost/   進入網站
http://localhost/mysql/   進入phpmyadmin管理mysql server
(mysql default user為root, 沒有password)

點選 Configure > Windows Hosts file
加入
127.0.0.1 www.mycookbook.com
127.0.0.1 typo

點選 Rails Applications > Manage Rails Applications...
然後選擇 cookbookc 並按下 "Start SCGI" button.
輸入 http://www.mycookbook.com/ 進入網站

在玩Rails前,先來認識一下Ruby:
在windows os下, 進入 cd/InstantRails/ruby/bin
執行:ruby -v
查看ruby版本
執行:irb
進入Ruby shell可進行邏輯運算
執行:irb --simple-prompt
然後輸入 print('Joeyta') 就可看到輸出

建主c:/joeyta.rb, 內容為:
print ("My name is:")         # 括孤可有可無
puts "Joeyta"                 # puts的輸出自動輸行
print "What is your name?/n"  # double quote可解釋escape字元
puts 'Peter Chan/n'           # single quote直接輸出所有字元
print '1+1 ='; puts 1+1       # 傳回 1+1=2
puts "abc"=="abc"             # 傳回true
a = "ab"; b = "ab"
puts "ab".eql?"ab"            # 傳回true,判斷實際值
puts "ab".equal?"ab"          # 傳回false,判斷參考位置
puts 10 > 50                  # 傳回false
puts "abcd".index('c')        # 傳回2

name = "joeyta"; 
printf("名: %s/n", name)      # printf可作格式化
printf("是否joeyta? %s/n", (name == 'joeyta' ? '是' : '否'))

number=gets.to_i              # gets取後輸入,to_i轉成數字,給變數number
puts number                 

if number == 1         # if表達式
 puts '輸入為1'
elsif number == 2
 puts '輸入為2'
else
 puts '輸入不為1,2'
end

unless number == 1            # number不為1時為true
 puts '輸出不為1'
else
 puts '輸出為1'
end

case number                   # case 表達式
 when 1
  puts 'case 1'
 when 2
  puts 'case 2'
 else
  puts 'case 1,2'
end

for i in 0..2
   print i,"/n"
end

for element in [0.2, 4, 'joeyta']   
 print "#{element}/t(#{element.class})/n"
end

(0..2).each {|i| puts i}
(9..12).each do |i| puts i end
2.times {puts "joeyta"}
3.times do |i| puts "peter" end

j = 1000
begin
 j -= 1
 puts j
 if j==997
  break
  end
end while j>=995               # 亦可使用until

(1..5).each do |num|
 print num   
 if num == 4         
  break                      # 亦可使用redo繼續, next下一個, retry重試迴路
 end                        
end

values = [2, 4, 6, 8, 10]
values.length.times do |index|   
print values[index], " "
end

ary = Array.new(3).fill { "foo" }
ary[0].replace "bar"
p ary

執行
c:/InstantRails/ruby/bin>ruby c:/joeyta.rb

玩完Ruby後,現在來玩一下Rails:
c:/InstantRails/ruby/bin>rails C:/InstantRails/rails_apps/mybook
就會在C:/InstantRails/rails_apps/ 目,建主mybook的application及相關的檔案

執行
ruby C:/InstantRails/rails_apps/mybook/script/server
或到Instant Rails > I > Rails Application > Manage Rails Applications
點選mybook 及 按 "Start with WEBrick"
就會啟動網站
輸入http://127.0.0.1:3000/ 進入網站

執行ruby C:/InstantRails/rails_apps/mybook/script/generate controller MyTest
編輯C:/InstantRails/rails_apps/mybook/app/controllers/my_test_controller.rb 為
class MyTestController < ApplicationController
 def index
   render_text "Hello World"
 end
end

輸入 http://127.0.0.1:3000/My_Test/ 就能看到 Hello World

繼續編輯 C:/InstantRails/rails_apps/mybook/app/controllers/my_test_controller.rb
class MyTestController < ApplicationController
 def index
   render_text "Hello World"
 end
 def hello
   render_text "Hello Rails"
 end
end

輸入 http://127.0.0.1:3000/My_Test/hello  就看到 Hello Rails

建立資料庫:
進入 http://localhost/mysql/

執行:
create database mybook;
create table books(
id int(11) auto_increment primary key,
title varchar(100),
description text,
buydate date)

修改 C:/InstantRails/rails_apps/mybook/config/database.yml 
(YAML配置檔,詳情可參考 http://www.yaml.org/ 及 http://www.ruby-doc.org/core/classes/YAML.html)
development:
  adapter: mysql
  database: mybook
  username: root
  password:
  host: localhost
test:
  adapter: mysql
  database: mybook
  username: root
  password:
  host: localhost
production:
  adapter: mysql
  database: mybook
  username: root
  password:
  host: localhost
 
執行
ruby C:/InstantRails/rails_apps/mybook/script/generate model book
就會在C:/InstantRails/rails_apps/mybook/app/models 下產生 book.rb
Rails智能地把Book mapping 至 mysql 的books table.
(創建model book就會將Book映射至英文眾數的book talbe,即books table)

執行
ruby C:/InstantRails/rails_apps/mybook/script/generate controller book
編輯 C:/InstantRails/rails_apps/mybook/app/controllers/book_controller.rb
class BookController < ApplicationController
 scaffold:book      # scaffold:book 產生CRUD代碼
end

輸入 http://127.0.0.1:3000/book/new
不可思意地竟然產生了UI 讓用戶新增 修改 刪除 數據到mysql books table.

編輯 C:/InstantRails/rails_apps/mybook/app/controllers/book_controller.rb
class BookController < ApplicationController
 scaffold:book
 def list
end
當輸入 http://127.0.0.1:3000/book/new 會出現缺少template的錯誤頁面

新增
C:/InstantRails/rails_apps/mybook/app/views/book/list.rhtml 內容為
<html>
<head>
<title>All books</title>
</head>
<body>
<h1>Online Mybook - All books</h1>
<table border="1">
<tr>
 <td width="80%"><p align="center"><i><b>book</b></i></td>
 <td width="20%"><p align="center"><i><b>Date</b></i></td>
</tr>
<% @books.each do |book| %>
<tr>
 <td><%= link_to book.title, :action => "show", :id => book.id %></td>
 <td><%= book.buydate %></td>
</tr>
<% end %>
</table>
<p><%= link_to "Create new book", :action => "new" %></p>
</body>
</html>

修改 C:/InstantRails/rails_apps/mybook/app/controllers/book_controller.rb
class BookController < ApplicationController
 scaffold:book
 def list
  @books = Book.find_all
 end
end

輸入 http://127.0.0.1:3000/book/list 就會出現自定的list template

進入 http://localhost/mysql/
use mybook;
create table categories(
 id int(11) auto_increment primary key,
 name varchar(50)
);
alter table books add category_id int(11) not null after description;
INSERT INTO `categories` VALUES (1, '小說');
INSERT INTO `categories` VALUES (2, '科幻');
INSERT INTO `categories` VALUES (3, '漫畫');
INSERT INTO `books` VALUES (1, '天海', '天海一閣', 1, '2006-04-28');
INSERT INTO `books` VALUES (2, '好書', '好書一本', 2, '2006-04-29');

執行
ruby C:/InstantRails/rails_apps/mybook/script/generate model category
ruby C:/InstantRails/rails_apps/mybook/script/generate controller category

修改 C:/InstantRails/rails_apps/mybook/app/model/book.rb
class Book < ActiveRecord::Base
 belongs_to :category
end

修改 C:/InstantRails/rails_apps/mybook/app/model/category.rb
class Category < ActiveRecord::Base
 has_many :books
end

修改 C:/InstantRails/rails_apps/mybook/app/controllers/book_controller.rb
class BookController < ApplicationController
 scaffold:book
 def list
  @books = Book.find_all
 end
 def edit
  @book = Book.find(@params["id"])
  @categories = Category.find_all
 end 
end

新增C:/InstantRails/rails_apps/mybook/app/views/book/list.rhtml 內容為
<html>
<head>
<title>Edit book</title></head>
<body>
<h1>Edit book</h1>
<form action="../update" method="POST">
 <input id="book_id" name="book[id]" size="30" type="hidden" value="<%= @book.id %>" />
 <p><b>Title</b><br>
  <input id="book_title" name="book[title]" size="30" type="text" value="<%= @book.title %>" /> </p>
 <p><b>Description</b><br>
   <input id="book_description" name="book[description]" size="30" type="text" value="<%= @book.description %>" /> </p>
 <p><b>Category:</b><br>
 <select name="book[category_id]">
  <% @categories.each do |category| %>
   <option value="<%= category.id %>" <%= ' selected' if category.id == @book.category.id %>> <%= category.name %>
   </option>
  <% end %>
 </select></p>
 <input type="submit" value="Update" />
</form>
 <a href="/book/show/<%= @book.id %>"> Show </a> | <a href="/book/list"> Back </a>
</body>
</html>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.