[Ruby on Rails 学习笔记] Chapter 1 从零到部署

691 阅读2分钟

Ruby on Rails 学习笔记

参考教材:Ruby on Rails 教程 原书第6版

Chapter 1 从零到部署

1.1 环境准备

Rails是Ruby语言的Web框架,需要先安装Ruby。具体安装方法详见官方网址ruby-china.github.io/rails-guide…,不再赘述。

gem是Ruby用来管理包的工具。其中,使用如下命令安装指定版本的Rails。

$ gem install rails -v 6.1.5.1

Bundler是一个安装gem包的工具。使用如下命令安装Bundler:

$ gem install bundler -v 2.2.13

Rails不需要额外指定的编辑器运行。IDE可以使用JetBrains公司的RubyMine。Windows配置Rails会遇到很多问题(比如需要单独下载sqlite3.h等文件),建议使用虚拟机或云服务器配置Rails运行环境,然后利用RubyMine的SSH远程开发功能连接服务器(VS Code有类似的功能),进行远程开发。

1.2 建立应用

Rails使用rails new命令新建web应用程序。以创建名为hello的应用程序为例。

$ rails new hello
     create
     create README.md
     create Rakefile
     ...

该命令会在当前目录下创建一个hello目录,并在其中自动生成所需的目录结构。Gemfile文件管理当前web项目所需要的gem包依赖。gem 'xxx', '=>1.4'表示安装版本号大于等于1.4。gem 'xxx', '~>1.4',表示安装版本号大于等于1.4但不高于2。如果后面不跟~>或者=>,则表示安装最新版本。经验告诉我们,即使是最小版本的升级也可能导致 Rails 应用无法运行,所以我们基本上会为所有的 gem 都指定精确的版本号。执行bundle install命令安装这些gem。

在中国大陆,使用 Bundler 安装 gem 的速度可能不理想,这时可以使用国内的镜像提速:

$ bundle config mirror.https://rubygems.org https://gems.ruby-china.com

1.3 在服务器上运行

在应用目录下运行rails server启动web服务器。可通过3000端口访问。

$ cd ~/hello/$ rails server
=> Booting Puma
=> Rails 6.1.5.1 application starting in development 
=> Run `bin/rails server --help` for more startup options
Puma starting in single mode...
* Puma version: 5.6.4 (ruby 2.7.0-p0) ("Birdie's Version")
*  Min threads: 5
*  Max threads: 5
*  Environment: development
*          PID: 1947987
* Listening on http://127.0.0.1:3000
* Listening on http://[::1]:3000

启动后,运行control+C停止。

如果需要连接本地服务器,需要在config/environments/development.rb中的Rails.application.configure do函数中添加一行config.hosts.clear

注意:部署时需要根据不同的场景需求,更改IP地址。如果只需要通过内网访问,则不需要改动(默认为127.0.0.1即localhost)。如果在公网中通过外部访问服务器,需要将host的IP地址改为0.0.0.0。在rails server后输入-b 0.0.0.0指定端口号。参考资料如下:

Binding to 0.0.0.0 tells the service to bind to all IP addresses on your machine. Rails server used to do this by default, but with 4.2 changed to binding only to localhost.

Basically if it's only bound to localhost then it will only respond locally to either localhost or 127.0.0.1 which can't work through a DNS service because it's not a public IP address.

When you use 0.0.0.0 it will bind to localhost and to your routable IP address.

Reference: stackoverflow.com/questions/2…