[Rails] 安裝並啟動 Rails 專案
建立 Rails 新專案流程
注意
下方流程使用 RVM 管理 Ruby 版本,以及 Ruby 2.6.3。目前社群更推薦使用 rbenv 或 asdf 管理 Ruby 版本,且建議使用 Ruby 3.x 搭配最新版 Rails。--webpack=react 旗標在 Rails 7 中已移除(Webpacker 被替換為 importmap 或 jsbundling-rails),--skip-coffee 也不再需要。建立 Rails 7+ 專案請參考官方文件的最新說明。
# 安裝 Ruby
$ rvm get stable # 更新 rvm 至最新版本
$ rvm list known # 取的目前最新版可用的 Ruby 版本
$ rvm install 2.6.3 # 安裝當前最新版的 Ruby
$ rvm use 2.6.3 --default # 使用最新版的 Ruby 並設為預設值
$ ruby -v # 確定使用的 Ruby 版本
# 如果有要使用 gemset 的話,否則可以跳過
$ rvm gemset create rails600
$ rvm use 2.6.3@rails600 # 選擇使用 Ruby 2.6.3 搭配 gemsets “rails600”
# 安裝 Rails 和 PostgreSQL 的 GEM
$ gem install rails --no-document # 若想要安裝到最新的開發版可以加上 --pre
$ gem install pg --no-document
$ gem install rails --pre # 安裝最新版(包含開發中版本)的 Rails
# 建立專案(Rails 6,--webpack 旗標在 Rails 7 中已移除)
$ rails new [projectName] --webpack=react --database=postgresql --skip-coffee --skip-test
# Scaffold
$ rails generate scaffold Product title:string description:text image_url:string price:decimal
建立 rake helper
可以寫一個 rake 來自動化執行:
# lib/tasks/dev.rake
namespace :dev do
desc 'Rebuild system'
task build: ['tmp:clear', 'log:clear', 'db:drop', 'db:create', 'db:migrate']
task rebuild: ['dev:build', 'db:seed']
end
這樣只要打
rails dev:build:即可把專案資料一切清空歸零重建rails dev:rebuild:即可重建完再跑 seed
使用 uuid 和 jsonb
使用 jsonb
$ rails g migration enable_hstore_extension
# migration 檔案中放入以下內容
class EnableHstoreExtension < ActiveRecord::Migration[6.0]
def change
enable_extension 'hstore'
end
end
使用 uuid
$ rails g migration enable_uuid_extension
# migration 檔案中放入以下內容
class EnableUuidExtension < ActiveRecord::Migration[6.0]
def change
enable_extension 'uuid-ossp'
enable_extension 'pgcrypto'
end
end
設定 webpack
過時內容
Webpacker 在 Rails 7 中已被正式移除,不再作為預設 JavaScript 打包工具。Rails 7 改為使用 importmap-rails(預設)、jsbundling-rails(搭配 esbuild/rollup/webpack)或 shakapacker(Webpacker 社群分支)。若使用 Rails 7+,請勿依照此章節設定。
# config/webpacker.yml
# 改成 true 後才會編譯出 CSS 「檔案」而不是 blob
# 可以避免重新整理時,因為 CSS 還沒載入完成導致畫面跳一下的情況
# Extract and emit a css file
extract_css: true