必要的环境
- 用 rbenv 安装 ruby
- 用 rvm 安装 node.js
- 安装 yarn
- Mac 自带 SQLite3
安装 ruby
rbenv install 3.0.3
安装 rails
gem install rails -v 7.0.0.rc1
初始化项目
初始化项目,启动项目
rails new rails-blog-1
cd rails-blog-1
bin/rails s
文章列表
在 config/routes.rb 添加路由
Rails.application.routes.draw do
get "/articles", to: "articles#index"
end
创建 Controller
bin/rails generate controller Articles index --skip-routes
编辑 app/views/articles/index.html.erb
<h1>Hello, Rails!</h1>
重启项目
打开文章列表:http://127.0.0.1:3000/articles,可看到 Hello, Rails!
编辑 config/routes.rb,设置首页
Rails.application.routes.draw do
root "articles#index"
get "/articles", to: "articles#index"
end
保存,重新打开 http://127.0.0.1:3000,页面显示和文章列表一样
创建 Model
bin/rails generate model Article title:string body:text
迁移数据
bin/rails db:migrate
往数据库插入一条数据
bin/rails console
article = Article.new(title: "Hello Rails", body: "I am on Rails!")
article.save
修改 app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
end
修改 app/views/articles/index.html.erb
<h1>Articles</h1>
<ul>
<% @articles.each do |article| %>
<li>
<%= article.title %>
</li>
<% end %>
</ul>
打开 http://127.0.0.1:3000 就能看见页面显示一条文章标题:Hello Rails
文章详情页
编辑路由 config/routes.rb
Rails.application.routes.draw do
root "articles#index"
get "/articles", to: "articles#index"
get "/articles/:id", to: "articles#show"
end
编辑 app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
end
新建 app/views/articles/show.html.erb
<h1><%= @article.title %></h1>
<p><%= @article.body %></p>
编辑 app/views/articles/index.html.erb
<h1>Articles</h1>
<ul>
<% @articles.each do |article| %>
<li>
<a href="/articles/<%= article.id %>">
<%= article.title %>
</a>
</li>
<% end %>
</ul>
现在打开 http://127.0.0.1:3000,点击文章标题,跳转到文章详情页,详情页展示文章标题和内容。
路由
编辑 config/routes.rb,用 resources 代替
Rails.application.routes.draw do
root "articles#index"
resources :articles
end
可以用下面命令查看路由:
bin/rails routes
编辑 app/views/articles/index.html.erb,替换 a 标签
<h1>Articles</h1>
<ul>
<% @articles.each do |article| %>
<li>
<%= link_to article.title, article %>
</li>
<% end %>
</ul>
打开 http://127.0.0.1:3000,内容没变。