这些只是几个大名。自 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.require(:article).permit(:title, :content)
end
end
控制器将域模型公开给 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 的全部多功能性,过多的代码提取到助手,域模型直接使用并与 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 如何连接到控制器。路由公开了一组作为资源组合在一起的操作:索引、显示、新建、创建、编辑、更新、销毁。
Rails 在一组广泛的异端思想周围团结和培养了一个强大的部落,这些思想涉及编程和程序员的本质。了解这些思想将有助于您理解该框架的设计。