Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

rails-style-guide

> 后端框架
Open source

:green_book: Russian Version: A community-driven Rails 3 & 4 & 5 style guide.

199 stars0 likes6 views
WebsiteGitHub

About

:green_book: Russian Version: A community-driven Rails 3 & 4 & 5 style guide.

= The Rails Style Guide :idprefix: :idseparator: - :sectanchors: :sectlinks: :toc: preamble :toclevels: 1 ifndef::backend-pdf[] :toc-title: pass:[ Table of Contents ] endif::[] :source-highlighter: rouge

== Introduction

[quote]


Role models are important.

-- Officer Alex J. Murphy / RoboCop


ifdef::env-github[] TIP: You can find a beautiful version of this guide with much improved navigation at https://rails.rubystyle.guide. endif::[]

The goal of this guide is to present a set of best practices and style prescriptions for Ruby on Rails 4 development. It's a complementary guide to the already existing community-driven https://github.com/rubocop-hq/ruby-style-guide[Ruby coding style guide].

This Rails style guide recommends best practices so that real-world Rails programmers can write code that can be maintained by other real-world Rails programmers. A style guide that reflects real-world usage gets used, and a style guide that holds to an ideal that has been rejected by the people it is supposed to help risks not getting used at all - no matter how good it is.

The guide is separated into several sections of related rules. I've tried to add the rationale behind the rules (if it's omitted I've assumed it's pretty obvious).

I didn't come up with all the rules out of nowhere - they are mostly based on my extensive career as a professional software engineer, feedback and suggestions from members of the Rails community and various highly regarded Rails programming resources.

NOTE: Some of the advice here is applicable only to Rails 4.0+.

You can generate a PDF copy of this guide using https://asciidoctor.org/docs/asciidoctor-pdf/[AsciiDoctor PDF], and an HTML copy https://asciidoctor.org/docs/convert-documents/#converting-a-document-to-html[with] https://asciidoctor.org/#installation[AsciiDoctor] using the following commands:

[source,shell]

Generates README.pdf

asciidoctor-pdf -a allow-uri-read README.adoc

Generates README.html

asciidoctor

[TIP]

Install the rouge gem to get nice syntax highlighting in the generated document.

[source,shell]

gem install rouge

====

Translations of the guide are available in the following languages:

  • https://github.com/JuanitoFatas/rails-style-guide/blob/master/README-zhCN.md[Chinese Simplified]
  • https://github.com/JuanitoFatas/rails-style-guide/blob/master/README-zhTW.md[Chinese Traditional]
  • https://github.com/satour/rails-style-guide/blob/master/README-jaJA.md[Japanese]
  • https://github.com/arbox/rails-style-guide/blob/master/README-ruRU.md[Russian]
  • https://github.com/tolgaavci/rails-style-guide/blob/master/README-trTR.md[Turkish]
  • https://github.com/pureugong/rails-style-guide/blob/master/README-koKR.md[Korean]
  • https://github.com/CQBinh/rails-style-guide/blob/master/README-viVN.md[Vietnamese]
  • https://github.com/abraaomiranda/rails-style-guide/blob/master/README-ptBR.md[Portuguese (pt-BR)]

TIP: https://github.com/rubocop-hq/rubocop[RuboCop], a static code analyzer (linter) and formatter, has a https://github.com/rubocop-hq/rubocop-rails[`rubocop-rails`] extension, based on this style guide.

== Configuration

=== Config Initializers [[config-initializers]]

Put custom initialization code in config/initializers. The code in initializers executes on application startup.

=== Gem Initializers [[gem-initializers]]

Keep initialization code for each gem in a separate file with the same name as the gem, for example carrierwave.rb, active_admin.rb, etc.

=== Dev/Test/Prod Configs [[dev-test-prod-configs]]

Adjust accordingly the settings for development, test and production environment (in the corresponding files under config/environments/)

Mark additional assets for precompilation (if any):

[source,ruby]

config/environments/production.rb

Precompile additional assets (application.js, application.css,

#and all non-JS/CSS are already added) config.assets.precompile += %w( rails_admin/rails_admin.css rails_admin/rails_admin.js )

=== App Config [[app-config]]

Keep configuration that's applicable to all environments in the config/application.rb file.

=== Load Rails Config Defaults [[config-defaults]]

When upgrading to a newer Rails version, your application's configuration setting will remain on the previous version. To take advantage of the latest recommended Rails practices, the config.load_defaults setting should match your Rails version.

[source,ruby]

good

config.load_defaults 6.1

=== Staging Like Prod [[staging-like-prod]]

Avoid creating additional environment configurations than the defaults of development, test and production. If you need a production-like environment such as staging, use environment variables for configuration options.

=== YAML Config [[yaml-config]]

Keep any additional configuration in YAML files under the config/ directory.

Since Rails 4.2 YAML configuration files can be easily loaded with the new config_for method:

[source,ruby]

Rails::Application.config_for(:yaml_file)

== Routing

=== Member Collection Routes [[member-collection-routes]]

When you need to add more actions to a RESTful resource (do you really need them at all?) use member and collection routes.

[source,ruby]

bad

get 'subscriptions/:id/unsubscribe' resources :subscriptions

good

resources :subscriptions do get 'unsubscribe', on: :member end

bad

get 'photos/search' resources :photos

good

resources :photos do get 'search', on: :collection end

=== Many Member Collection Routes [[many-member-collection-routes]]

If you need to define multiple member/collection routes use the alternative block syntax.

[source,ruby]

resources :subscriptions do member do get 'unsubscribe' # more routes end end

resources :photos do collection do get 'search' # more routes end

end

=== Nested Routes [[nested-routes]]

Use nested routes to express better the relationship between Active Record models.

[source,ruby]

class Post

", type: :erb end end

good

app/views/products/index.html.erb

app/views/products/_product.html.erb

app/controllers/products_controller.rb

class ProductsController { where(active: true) } scope :inactive, -> { where(active: false) }

scope :with_orders, -> { joins(:orders).select('distinct(users.id)') } end

=== Named Scope Class [[named-scope-class]]

When a named scope defined with a lambda and parameters becomes too complicated, it is preferable to make a class method instead which serves the same purpose of the named scope and returns an ActiveRecord::Relation object. Arguably you can define even simpler scopes like this.

[source,ruby]

class User 21').each do |person| person.party_all_night! end

good

Person.find_each do |person| person.do_awesome_stuff end

Person.where('age > 21').find_each do |person| person.party_all_night! end

=== before_destroy [[before_destroy]]

Since https://github.com/rails/rails/issues/3458[Rails creates callbacks for dependent associations], always call before_destroy callbacks that perform validation with prepend: true.

[source,ruby]

bad (roles will be deleted automatically even if super_admin? is true)

has_many :roles, dependent: :destroy

before_destroy :ensure_deletable

def ensure_deletable raise "Cannot delete super admin." if super_admin? end

good

has_many :roles, dependent: :destroy

before_destroy :ensure_deletable, prepend: true

def ensure_deletable raise "Cannot delete super admin." if super_admin? end

=== has_many/has_one Dependent Option [[has_many-has_one-dependent-option]]

Define the dependent option to the has_many and has_one associations.

[source,ruby]

bad

class Post = ? AND created_at = :start_date AND created_at { order(id: :asc) }

good

scope :chronological, -> { order(created_at: :asc) }

=== pluck

Use https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pluck[pluck] to select a single value from multiple records.

[source,ruby]

bad

User.all.map(&:name)

bad

User.all.map { |user| user[:name] }

good

User.pluck(:name)

=== pick

Use https://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-pick[pick] to select a single value from a single record.

[source,ruby]

bad

User.pluck(:name).first

bad

User.first.name

good

User.pick(:name)

=== ids [[ids]]

Favor the use of ids over pluck(:id).

[source,Ruby]

bad

User.pluck(:id)

good

User.ids

=== Squished Heredocs [[squished-heredocs]]

When specifying an explicit query in a method such as find_by_sql, use heredocs with squish. This allows you to legibly format the SQL with line breaks and indentations, while supporting syntax highlighting in many tools (including GitHub, Atom, and RubyMine).

[source,ruby]

User.find_by_sql(.rb

frozen_string_literal: true

bad

class ModifyDefaultStatusForProducts


== Internationalization

=== Locale Texts [[locale-texts]]

No strings or other locale specific settings should be used in the views, models and controllers. These texts should be moved to the locale files in the config/locales directory.

=== Translated Labels [[translated-labels]]

When the labels of an Active Record model need to be translated, use the activerecord scope:


en: activerecord: models: user: Member attributes: user: name: 'Full name'


Then User.model_name.human will return "Member" and User.human_attribute_name("name") will return "Full name". These translations of the attributes will be used as labels in the views.

=== Organize Locale Files [[organize-locale-files]]

Separate the texts used in the views from translations of Active Record attributes. Place the locale files for the models in a folder locales/models and the texts used in the views in folder locales/views.

When organization of the locale files is done with additional directories, these directories must be described in the application.rb file in order to be loaded.

[source,ruby]

config/application.rb

config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

=== Shared Localization [[shared-localization]]

Place the shared localization options, such as date or currency formats, in files under the root of the locales directory.

=== Short I18n [[short-i18n]]

Use the short form of the I18n methods: I18n.t instead of I18n.translate and I18n.l instead of I18n.localize.

=== Lazy Lookup [[lazy-lookup]]

Use "lazy" lookup for the texts used in views. Let's say we have the following structure:


en: users: show: title: 'User details page'


The value for users.show.title can be looked up in the template app/views/users/show.html.haml like this:

[source,ruby]

= t '.title'

=== Dot-separated Keys [[dot-separated-keys]]

Use the dot-separated keys in the controllers and models instead of specifying the :scope option. The dot-separated call is easier to read and trace the hierarchy.

[source,ruby]

bad

I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]

good

I18n.t 'activerecord.errors.messages.record_invalid'

=== I18n Guides [[i18n-guides]]

More detailed information about the Rails I18n can be found in the https://guides.rubyonrails.org/i18n.html[Rails Guides]

== Assets

Use the https://guides.rubyonrails.org/asset_pipeline.html[asset pipeline] to leverage organization within your application.

=== Reserve app/assets [[reserve-app-assets]]

Reserve app/assets for custom stylesheets, javascripts, or images.

=== lib/assets [[lib-assets]]

Use lib/assets for your own libraries that don't really fit into the scope of the application.

=== vendor/assets [[vendor-assets]]

Third party code such as https://jquery.com/[jQuery] or https://twitter.github.com/bootstrap/[bootstrap] should be placed in `vendor/a

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubybbatsovrailsrubystyle-guide

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架