Fix error: rails console No such file to load -- irb/encoding_aliases.rb (LoadError)

I got this error after upgrading Ruby from 2.4.5 to 2.6.4 when I opened the Rails console - rails server still worked.

Running via Spring preloader in process 14679
Loading development environment (Rails 5.2.2.1)
Traceback (most recent call last):
.../lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/application.rb:175:in 'fork': No such file to load -- irb/encoding_aliases.rb (LoadError)
.../lib/ruby/gems/2.6.0/gems/spring-2.1.0/lib/spring/application.rb:175:in 'fork': undefined method 'reject!' for nil:NilClass (NoMethodError)
.../li...

Sharing cookies across subdomains with Rails 3

To achieve this goal you have to setup the session store like the following example:

  MyApp::Application.config.session_store(
    :cookie_store,
    {
      :key => '_myapp_session',
      :domain => :all, # :all defaults to da tld length of 1, '.web' has length of 1
      :tld_length => 2 # Top Level Domain (tld) length -> '*.myapp.web' has a length of 2
    }
  )

The invconvenient side effect for local development

… or: Why do I get "Can't verify CSRF token authenticity" even if csrf token is present?

As `:domain => :all...

Speed up file downloads with Rails, Apache and X-Sendfile

When you use the send_file method to send a local file to the browser, you can save resources on the application server by setting the :x_sendfile option to true. This option is activated by default for Rails 3, so you need to understand this.

What this option does is not to send any data at all, but rather set the local file path as a new response header:

X-Sendfile: /opt/www/awesome-project/shared/downloads/image.png

When the response comes back from Rails to...

Test a gem in multiple versions of Rails

Plugins (and gems) are typically tested using a complete sample rails application that lives in the spec folder of the plugin. If your gem is supposed to work with multiple versions of Rails, you might want to use to separate apps - one for each rails version.

For best practice examples that give you full coverage with minimal repitition of code, check out our gems has_defaults and assignable_values. In particular, take a look at:

  • Multiple `sp...

Rails 2: Refuse response formats application-wide

If you regularly get ActionView::MissingTemplate exceptions, maybe some bot visits your site requesting silly formats like:

http://www.rails-app.com/makandra.html-username-2000 # => Rails tries to retrieve 'makandra' with format 'html-username-2000'

Just restrict accepted format parameters for the whole application like this:

class ApplicationController < ActionController::Base

  before_filter :refuse_silly_formats

  private

  def refuse_silly_formats
    acceptable_formats = %w[html xml pdf]

    if par...

Beware of rails' reverse_order!

#reverse_order does not work with complex sorting constraints and may even silently create malformed SQL for rails < 5.

Take a look at this query which orders by the maximum of two columns:

Page.order('GREATEST(pages.published_from_de, pages.published_from_en) DESC').to_sql
# => SELECT "pages".* FROM "pages" ORDER BY GREATEST(pages.published_from_de, pages.published_from_en) DESC

Rails 4

Rails 4 will not immediately raise but creates malformed SQL when trying to use reverse_order on this query:

Pageorder('GRE...

Using Spring and parallel_tests in your Rails application

You want Spring for super-fast binstubs like bin/rails or bin/rspec which avoid Rails boot time.
You want parallel_tests to speed up full test runs of large test suites.

Unfortunately, you do not want parallel_tests to use your Spring binstubs as those parallelized tests will share data and/or loose some information. There are some issues about this on GitHub and there is a suggested [workaround](https:...

Accessing Rails config in webpack(er)

It is possible to access Rails config (for example secrets) from within your webpack bundles, thanks to rails-erb-loader. When using webpacker, the setup is like this:

  1. Install rails-erb-loader:

    yarn add rails-erb-loader
    
  2. Add this to your config/webpacker/environment.js:

    environment.loaders.prepend('erb', {
      test: /\.erb$/,
      enforce: 'pre',
      use: [{
        loader: 'rails-erb-loader',
      }]
    })
    
  3. Start using erb. For examp...

How to debug Rails autoloading

ActiveSupport::Dependencies takes care of auto-loading any classes in development. This is usually useful, but when you run into issues with the Rails autoloader, you should take a look at what it's doing.

For me this was useful in an "exciting" case of auto-loading classes inside a thread which caused the application to stop responding.

Rails 4.x

ActiveSupport::Dependencies includes logging support. It is easy to use:

ActiveSupport::Dependencies.logger = Rails.logger

Rails 5+

[Logging support was removed](https://github...

Rails - Multi Language with Fast_Gettext

  • sudo gem install gettext --no-ri --no-rdoc
  • sudo gem install fast_gettext --no-ri --no-rdoc
  • script/plugin install git://github.com/grosser/gettext_i18n_rails.git (didn't work as gem)
  • environment.rb: see code example at the bottom
  • if this is your first translation: cp locale/app.pot locale/de/app.po for every locale you want to use
  • use method "_" like _('text') in your rails code
  • run rake gettext:find to let GetText find all translations used
  • translate messages in 'locale/de/app.po' (leave msgstr blank and ms...

Rails Assets

Automatically builds gems from Bower packages (currently 1700 gems available). Packaged Javascript files are then automatically available in your asset pipeline manifests.

Why we're not using it

At makandra we made a choice to use bower-rails instead. While we believe Rubygems/Bundler to be superior to Javascript package managers, we wanted to use something with enough community momentum behind it that it won't go away in 10 years...

Rails 3: Make "link_to :remote => true" replace HTML elements with jQuery

In Rails 2, you could use link_to_remote ... :update => 'id' to automatically replace the content of $('#id').

To do the same in Rails 3, include usual rails-ujs JavaScript, and put this into your application.js:

$(function() {
  $('[data-remote][data-replace]')
    .data('type', 'html')
    .live('ajax:success', function(event, data) {
      var $this = $(this);
      $($this.data('replace')).html(data);
      $this.trigger('ajax:replaced');...

Heads up! Years are always floats in Rails < 4

Watch out when saying something like 1.year in Rails. The result is not a Fixnum and can cause unexpected errors when the receiving end expects a Fixnum.

While anything from seconds to months are Fixnums, a year is a Float in Rails -- when called on a Fixnum itself:

>> 10.seconds.class
=> Fixnum
>> 2.minutes.class
=> Fixnum
>> 24.hours.class
=> Fixnum
>> 28.days.class
=> Fixnum
>> 9.months.class
=> Fixnum
>> 1.year.class
=> Float # Boom.

While they are [technically correct](http:...

MySQL: How to create columns like "bigint" or "longtext" in Rails migrations, and what :limit means for column migrations

Rails understands a :limit options when you create columns in a migration. Its meaning depends on the column type, and sometimes the supplied value.

The documentation states that :limit sets the column length to the number of characters for string and text columns, and to the number of bytes for binary and integer columns.

Using it

This is nice since you may want a bigint column to store really long numbers in it. You can just create it by ...

Render a view from a model in Rails

In Rails 5 you can say:

ApplicationController.render(
  :template => 'users/index',
  :layout => 'my_layout',
  :assigns => { users: @users }
)

If a Request Environment is needed you can set attributes default attributes or initialize a new renderer in an explicit way (e.g. if you want to use users_url in the template):

ApplicationController.renderer.defaults # =>
{
  http_host: 'example.org',
  https:      false,
  ...
}
...

Rails: wrap_parameters for your API

Rails 5 (don't know about the others) comes with an initializer wrap_parameters.rb. Here you can tell rails to wrap parameters send to your controllers for specific formats into a root node which it guesses from the controller name.

ActiveSupport.on_load(:action_controller) do
  wrap_parameters format: [:json]
end

This would wrap a flat json body, like

{"name": "Konata"}

that gets send to your UsersController into

{"name" => "Konata", "user" => {"name" => "Konata"}}

Note that the params are now duplicat...

Don't name columns like counter_cache columns in Rails pre v4.2.4

< Rails v4.2.4

ActiveRecord has a feature called counter caching where the containing record in a has_many relationship caches the number of its children. E.g. when you have House has_many :rooms, Rails can cache the number of rooms in House#rooms_count.

Mind that when a model has a column that looks to Rails like a counter-cache column, Rails will apply counter-cache logic to your model, even if you're not using counter caches.

E.g. you have a house with 12...

How to split config/routes.rb in Rails 4

A word of caution

There should rarely be a reason for you to split up config/routes.rb. If you need to, probably your whole application should be split up.

Split it anyway

Rails::Engine looks at config.paths['config/routes.rb'] and registers its value with app.routes_reloader. This means you could put routing files anywhere and then require them. However, I recommend to put any routing files into config/routes/:

# config/routes/example.rb

Rails.application.routes.draw do
 resources :example
end

After creating y...

Riding Rails: Rails 3.0: It's ready!

Rails 3.0 has been underway for a good two years, so it’s with immense pleasure that we can declare it’s finally here. We’ve brought the work of more than 1,600 contributors together to make everything better, faster, cleaner, and more beautiful.

RailsLab .:. Scaling Rails - Scaling Rails Screencasts

Learn everything you need to know about Scaling your Rails app through 13 informative Screencasts produced by Gregg Pollack with the support of New Relic.

Building and Scaling a Startup on Rails: 12 Things We Learned the Hard Way - Axon Flux - A Ruby on Rails Blog

There are a bunch of basic functional elements to building out a popular Rails app that I've never really seen explained in one place, but we had to learn the hard way while building Posterous.

Ruby on Rails Tutorial: Learn Rails by Example | by Michael Hartl

A thorough introduction to web development with Ruby on Rails

Managing vendor assets in Rails with Bower

bower-rails is a great solution for managing vendored assets in your Rails app. It feels especially much more convenient and easier to update assets when going this way.

bower-rails generates a Bowerfile that works much like the Gemfile you're used to. Just specify your dependencies and run rake bower:install. You can find available packages here.

An example Bowerfile:

# ./Bowerfile
asset 'angular'
asset 'angular-i18n'
asset 'angular-ui-router'
asset 'angu...