Ruby On Rails 笔记1——Rails 入门

突然想跟着官方文档把Ruby On Rails过一遍,把一些有用的记下来就可以一直看了,do它! https://guides.rubyonrails.org/v7.2/

注:官网是英文文档,我自己翻译了一下,不确保完全准确,只供自己学习开发使用。

Rails is a web application framework running on the Ruby programming language. There are several curated lists of online resources for learning Ruby:

1.Rails 是什么?

Rails是一个由Ruby编程语言编写的Web应用开发框架。它是为了让编写Web应用更简单而设计

2. Say "Hello", Rails

在完成安装启动后,想开始写代码了,you need to create at minimum a route, a controller with an action, and a view. A route将请求映射到controller action; A controller action里有处理请求的工作,以及给View准备的数据。A view根据需要的格式显示数据。

Step1 在routes文件里添加一个route

ruby 复制代码
Rails.application.routes.draw do
  get "/articles", to: "articles#index"

  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

这个route声明将GET /articles请求映射到ArticlesController 的index action.

Step2 通过下面这个命令生成ArticlesController和index

ruby 复制代码
bin/rails generate controller Articles index --skip-routes

生成的文件长这样app/controllers/articles_controller.rb

ruby 复制代码
class ArticlesController < ApplicationController
  def index
  end
end

默认情况下,Rails会自动render与controller 和 action名字相同的view,即app/views/articles/index.html.erb

Step3 在index.html.erb文件里写上

ruby 复制代码
<h1>Hello, Rails!</h1>

接下来启动server访问http://localhost:3000/articles就可以了。

也可以通过添加route

ruby 复制代码
root "articles#index"

将其设置成home page, 即访问http://localhost:3000就能打开index.html.erb文件.

3. 生成一个Model

上述提到routes, controllers, actions, and views,这些都是遵循MVC (Model-View-Controller)模式的Web应用典型组成部分。我们已经拥有了Controller和View,继续生成一个Model吧。

A model is a Ruby class that is used to represent data. Additionally, models can interact with the application's database through a feature of Rails called Active Record.

英文原文太好了,不翻译了。可以跟官网一样用model generator也可以自己创建app/models/article.rb。

可以根据数据库里需要存的字段定义这个model

至此最基本的概念和架构已经清楚了。

相关推荐
xuhaoyu_cpp_java4 小时前
项目学习(三)分页查询
java·经验分享·笔记·学习
Cloud_Shy6187 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
做cv的小昊7 小时前
计算机图形学:【Games101】学习笔记08——光线追踪(辐射度量学、渲染方程与全局光照、蒙特卡洛积分与路径追踪)
图像处理·笔记·学习·计算机视觉·游戏引擎·图形渲染·概率论
星恒随风7 小时前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
伊布拉西莫11 小时前
【流畅的Python】第20章:并发执行器 — 学习笔记
笔记·python·学习
AOwhisky13 小时前
学习自测与解析:MySQL第五、六、七期核心知识点详解
运维·数据库·笔记·学习·mysql·云计算
niuniuyi~13 小时前
QT学习笔记
笔记·qt·学习
咸甜适中13 小时前
rust语言学习笔记Trait(十六)Error(错误)
笔记·学习·rust
xuhaoyu_cpp_java14 小时前
项目学习(三)代码生成器
java·经验分享·笔记·学习
my_daling14 小时前
松下伺服驱动器参数保存流程(已在松下A5上验证)
笔记