这只是其中一些知名公司。 自成立以来,Rails 已创建了数十万个应用程序。
渲染 HTML 模板、更新数据库、发送和接收电子邮件、通过 WebSockets 维护实时页面、为异步工作排队任务、在云端存储上传的文件、为常见攻击提供坚实的安全性防护。Rails 能够做到这一切,以及更多。
class Article < ApplicationRecord
belongs_to :author, default: -> { Current.user }
has_many :comments
has_one_attached :cover_image
has_rich_text :content, encrypted: true
enum status: %i[ drafted published ]
scope :recent, -> { order(created_at: :desc).limit(25) }
after_save_commit :deliver_later, if: :published?
def byline
"Written by #{author.name} on #{created_at.to_s(:short)}"
end
def deliver_later
Article::DeliveryJob.perform_later(self)
end
end数据库通过封装在丰富对象中的业务逻辑而变得生动。建模表之间的关联、提供保存时的回调、无缝加密敏感数据,以及优美地表达 SQL 查询。
class ArticlesController < ApplicationController
def index
@articles = Article.recent
end
def show
@article = Article.find(params[:id])
fresh_when etag: @article
end
def create
article = Article.create!(article_params)
redirect_to article
end
private
def article_params
params.expect(article: [ :title, :content ])
end
endController 将领域模型暴露给 Web,处理传入参数,设置缓存头,并渲染模板,响应 HTML 或 JSON。
<h1><%= @article.title %></h1>
<%= image_tag @article.cover_image.url %>
<p><%= @article.content %></p>
<%= link_to "Edit", edit_article_path(@article) if Current.user.admin? %>模板可以使用 Ruby 的全部灵活性,冗余代码被提取到助手(helpers)中,并且领域模型被直接使用并与 HTML 交织在一起。
Rails.application.routes.draw do
resources :articles do # /articles, /articles/1
resources :comments # /articles/1/comments, /comments/1
end
root to: "articles#index" # /
end使用路由领域语言配置 URL 如何连接到控制器。路由公开了作为资源组合在一起的操作集合:index、show、new、create、edit、update、destroy。
Rails 围绕着一套关于编程和程序员本质的广泛的“异端”思想团结并培养了一个强大的社群。理解这些思想将帮助你理解框架的设计。
了解更多关于 Hotwire 的信息,它是 Rails 的默认前端框架。
在 X、YouTube 和 This Week in Rails 上及时了解 Rails 的最新动态。