記錄 Rails 開發環境建置(Windows)與標準開發流程,避免重複踩坑。涵蓋 Ruby/Rails 安裝、DevKit、NetBeans 整合、MySQL 設定、專案建立、Scaffold 快速原型、驗證、關聯、路由設定全過程。
rubyinstaller-1.9.2(含 RubyGems)gem install railsmysql2 0.2.6 支援 MySQLrails new blog
development:
adapter: mysql2
encoding: utf8
database: blog_development
username: root
password: 1234
host: localhost
rake db:create # 依 database.yml 自動建庫,無需手動
rails server
# 瀏覽 https://127.0.0.1:3000 確認環境變數正常
rails generate controller home index
# 刪除 public/index.html
# config/routes.rb
root :to => "home#index"
rails generate scaffold Post name:string title:string content:text
rake db:migrate # 同步 Schema 至資料庫
<!-- app/views/home/index.html.erb -->
<h1>Hello, Rails!</h1>
<%= link_to "My Blog", posts_path %>
class Post < ActiveRecord::Base
validates :name, :presence => true
validates :title, :presence => true, :length => { :minimum => 5 }
end
rails generate model Comment commenter:string body:text post:references
# 自動產生 belongs_to :post
rake db:migrate
class Post < ActiveRecord::Base
has_many :comments
# 驗證...
end
class Comment < ActiveRecord::Base
belongs_to :post
end
resources :posts do
resources :comments
end
rails generate controller Comments
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment])
redirect_to post_path(@post)
end
end
<!-- app/views/posts/show.html.erb -->
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<div class="field">
<%= f.label :commenter %><br/>
<%= f.text_field :commenter %>
</div>
<div class="field">
<%= f.label :body %><br/>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
| 任務 | 指令 |
|---|---|
| 建立專案 | rails new app_name |
| 產生 Scaffold | rails g scaffold Model field:type ... |
| 產生 Model | rails g model Model field:type ... |
| 產生 Controller | rails g controller Name action1 action2 |
| 執行遷移 | rake db:migrate |
| 回滾遷移 | rake db:rollback |
| 建立資料庫 | rake db:create |
| 啟動伺服器 | rails s |
| 進入 Console | rails c |
mysql2 ~> 0.2.x,新版不相容gem install mysql2 會報編譯錯誤database.yml 必須設 encoding: utf8root :to 應置於 routes.rb 早期posts_path vs post_comments_path(@post) 區分清楚Rails 開發流程極度標準化:資料庫設定 → 遷移 → Scaffold → 驗證 → 關聯 → 巢狀路由 → Controller/View 微調。掌握這套流程,即可在數分鐘內產出功能完整的 CRUD 原型,再疊加業務邏輯逐步演進為正式產品。