弄了好幾天,Ror環境終於搭好了,為了防止以後忘記,少走彎路,特記錄下
=============================================
安裝過程
1、安裝 rubyinstaller-1.9.2
2、安裝 執行 gem install rails
3、安裝 dev kit 下載後 解壓到ruby 的安裝目錄
4、安裝Netbeans 6.9.1
5、開啟Netbeans 配置 Ruby 的gem 重點 mysql2 0.2.6 讓ror 支援 mysql
6、安裝 ruby_debug_ide (還沒有搞定,一直報錯)
開發過程
1、建立項目 (Blog)
2、配置database.yam
3、執行rake 任務 db:create (會根據database.yam 在mysql 中建立資料庫,不用去手動建立資料庫)
4、啟動服務,開啟頁面,看是否正常 尤其是看環境變數是否正正確顯示
5、建立 controller home index
6、開啟服務 http://127.0.0.1:3000/home/index 看是否正常
7、更改預設首頁 (1、刪除public\index.html 2、更改routes 中的 root :to => "home#index")
8、建立腳手架模型( generate scaffold Post name:string title:string content:text)
9、執行 rake 任務,將新的資料模型同步到資料庫中 rake db:migrate
10、在首頁上 增加 到腳手架的連結 (在 views\home\index.html.erb 中修改為
<h1>Hello, Rails!</h1> <%= link_to "My Blog",
posts_path %>
注意裡面的 posts_path,約定的寫法
11、開啟首頁http://127.0.0.1:3000/ 看到有到blog的超級連結
12、連進去進行CURD測試。
13、在模型檔案中增加驗證資訊
class Post < ActiveRecord::Base validates :name , :presence => true validates :title , :presence => true , :length => { :minimum => 5 } end |
presence 表示是否可為空白,length 代表欄位的長度
14、測試是否有驗證資訊顯示。
15、建立一個普通model Comment (文章評論)
$ rails generate model Comment commenter:string body:text post:references
注意 post:references
16、在Post模型中自動產生了一對多的關係
class Comment < ActiveRecord::Base belongs_to :post end |
17、執行 rake ,任務 將新的資料模型同步到資料庫中 rake db:migrate
18、修改 Post 模型 增加一對多映射
class Post < ActiveRecord::Base validates :name , :presence => true validates :title , :presence => true , :length => { :minimum => 5 } has_many :comments end |
19、在 route 中配置 Comments映射(有待研究)
resources :posts do resources :comments end |
20、建立controller
$ rails generate controller Comments |
21、修改views/posts/show.html.erb,增加 對 Comment 的編輯
<
p
class
=
"notice"
>
<%=
notice
%>
</
p
>
<
p
>
<
b
>Name:</
b
>
<%=
@post
.name
%>
</
p
>
<
p
>
<
b
>Title:</
b
>
<%=
@post
.title
%>
</
p
>
<
p
>
<
b
>Content:</
b
>
<%=
@post
.content
%>
</
p
>
<
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
%>
<%=
link_to
'Edit Post'
, edit_post_path(
@post
)
%>
|
<%=
link_to
'Back to Posts'
, posts_path
%>
|
22、修改 commentcontroller
class CommentsController < ApplicationController def create @post = Post.find(params[ :post_id ]) @comment = @post .comments.create(params[ :comment ]) redirect_to post_path( @post ) end end |
23、先寫道這裡了
具體參考 http://guides.rubyonrails.org/getting_started.html