Ruby On Rails 安装手记

弄了好几天,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

posted @ 2011-07-29 20:50  疾行者  阅读(243)  评论(0编辑  收藏  举报