这些只是一些知名的. 自 Rails 诞生以来,已经有成千上万的应用程序使用 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
控制器将领域模型暴露给网络,处理传入参数,设置缓存标头,呈现模板,以 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 团结并培养了一个强大的部落,围绕着关于编程和程序员本质的 各种异端思想。理解这些思想将有助于你理解框架的设计.
详细了解Rails 的默认前端框架 Hotwire.
与 Rails on保持同步 在 Twitter 和 This Week in Rails.