Cheat Sheet速查表
跳转到主要内容

Rails 技巧 速查表

本文根据 Devhints / Rails tricks 翻译。代码示例及版本范围沿用原文。此资料为归档或旧版本参考。

原文归档说明:本速查表中的做法可能已过时。

Sass 源映射(source maps)

在 config/environments/development.rb 中:

# Source maps for Sass
config.sass.debug_info = true
config.sass.line_comments = false

# Don't break apart
config.assets.debug = false

局部模板(Partial)的局部变量

<%= render 'article', full: true %>
<%= render 'article' %>

<% if local_assigns[:full] %>
  ...
<% end %>

i18n 中的 HTML

en:
  read_more_html: "read <b>more</b>..."

异常处理

# config/application.rb
config.exceptions_app = self.routes

get '/404', to: 'errors#not_found'
get '/500', to: 'errors#server_error'

class ErrorsController
  def not_found
    render status: :not_found
  end
 end

更新 Rails

rake rails:update

去重提取(Distinct pluck)

Article.distinct.pluck('author')

Relation#merge

scope :with_drafts, -> {
  uniq.joins(:articles).merge(Article.draft)
}

排序 (Order)

scope :recent, -> { order created_at: :desc }

按月分组

.group("to_char(created_at, 'YYYY-MM')")
.group("to_char(created_at, 'YYYY-MM')").count