Ruby on Rails 遵循 MVC模式
Models Views Controllers
0 rails项目文件夹
app/
-assets
--config
--images (layout)
--stylesheets (.css)
-channels (communication)
-controllers
-helpers (help with views)
-javascript
-models
-views
--layout
bin/
config/
-environment
credentials.yml.enc
routes.rb
...
db/
migration files
Gemfile --> Gemfile.lock
README.md
.ruby-version
.gitignore
1 初始页面配置
/config/routes.rb
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
# root "articles#index"
# root "application#hello"
# root: 首页 -- http://localhost:3000/
root "pages#home"
# 页面跳转:http://localhost:3000/articles
get "/articles", to: "articles#index"
# 传参 http://localhost:3000/articles/1
get "/articles/:id", to: "articles#show"
# 为 CRUD 提供 映射
# maps all of the conventional routes for a collection of resources :articles
resources :articles
end
2 页面内容配置 Controller
# 新建 controller
# 会在 app/controllers, app/views/, test/controllers, app/helpers/ 下新建相关文件
# app/controllers/pages_controller.rb
# app/views/pages
# test/controllers/pages_controller_test.rb
# app/helpers/pages_helper.rb
rails generate controller pages
Controller: app/controllers/pages_controller.rb
View: app/views/pages/home.html.erb (手动自建)
Model: page.rb
4 Model
rails generate scaffold Article title:string description:text
--------------------------------------------------------------
invoke active_record
create db/migrate/20220428164030_create_articles.rb
create app/models/article.rb
invoke test_unit
create test/models/article_test.rb
create test/fixtures/articles.yml
invoke resource_route
route resources :articles
invoke scaffold_controller
create app/controllers/articles_controller.rb
invoke erb
create app/views/articles
create app/views/articles/index.html.erb
create app/views/articles/edit.html.erb
create app/views/articles/show.html.erb
create app/views/articles/new.html.erb
create app/views/articles/_form.html.erb
create app/views/articles/_article.html.erb
invoke resource_route
invoke test_unit
create test/controllers/articles_controller_test.rb
create test/system/articles_test.rb
invoke helper
create app/helpers/articles_helper.rb
invoke test_unit
invoke jbuilder
create app/views/articles/index.json.jbuilder
create app/views/articles/show.json.jbuilder
create app/views/articles/_article.json.jbuilder
# 生成表
rails db:migrate
# 查看 routes
rails routes --expanded
拓展
1 vscode标签自动补全
"emmet.triggerExpansionOnTab": true,
"emmet.includeLanguages": {
"*.erb": "html",
"ruby": "html"
}
2 免费网站host
3 版本控制 version control
# 配置列表
git config --list
# 新增文件
git add -A
# 查看状态
git status
# commit
git commit -m "Initial commit and add root route"