Notes posted to Ruby on Rails

RSS feed
August 5, 2014
0 thanks

simple use


<%= @user.created_at.to_date.to_formatted_s(:long_ordinal)%> => July 5th, 2014


<%=@user.created_at.strftime("%b %d,%Y") %> =>  Jul 05,2014

quick ref:-

:db           # => 2008-12-25 14:35:05
:number       # => 20081225143505
:time         # => 14:35
:short        # => 25 Dec 14:35
:long         # => December 25, 2008 14:35
:long_ordinal # => December 25th, 2008 14:35
:rfc822       # => Thu, 25 Dec 2008 14:35:05 +0000
July 30, 2014 - (>= v4.0.2)
0 thanks

4.0.2 support

Where did this go in 4.0.2?

July 23, 2014 - (v3.2.1)
0 thanks

form_for with namescope and polymorphic path

<%= form_for([:namescope_name, @object], :url => polymorphic_path([:namescope_name, @objectable, @object])) do |form| %>

for the routes.

namescope :admin do

resources :articles do
  resources :comments
resources :photos do
  resources :comments


<%= form_for([:admin, @comment], :url => polymorphic_path([:admin, @commentable, @comment])) do |form| %>

Note : @commentable = find_commentable

July 20, 2014
0 thanks

change_column did the trick for me

Use change_column, and make sure to specify the datatype:

class ChangeUsers < ActiveRecord::Migration
  def up
	change_column :users, :is_vote_reminder, :boolean, :default => true
July 11, 2014
1 thank

Use this for has_one associations instead

I have confirmed that validates_associated doesn’t work with has_one associations, like @amasses said.

This however worked for me, so I recommend to use validates on the has_one association directly, like this:

class Book < ActiveRecord::Base
  has_one :cover, validates: true
July 2, 2014 - (v3.2.1 - v4.0.2)
0 thanks

URI Module

Uniform handling of handling URIs

Flexibility to introduce custom URI schemes

Flexibility to have an alternate URI::Parser

For Example

require ‘uri’

uri = URI(“http://test.com/posts?id=30&limit=5#time=1305298413”)

uri.scheme #=> “http”

uri.host #=> “test.com”

uri.path #=> “/posts”

July 2, 2014
0 thanks

time is represented in the Rails app's timezone

From the description of Time.current (which is a Rails extension of Ruby’s native Time class)

“Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now.”

so 3.days.ago, for example, is in the application’s configured timezone (if it’s configured).

June 5, 2014
0 thanks

Reject If

reject_if: proc { |attributes| attributes[‘name’].blank? } Has saved me after an 3 hours of google search. Thanks

June 1, 2014 - (v4.0.2)
1 thank

Alternitive to to add flash to respond with

This is a nice way to add flash if you don’t have a any logic that needs to go around your flash.

def destroy
  respond_with @current_user_session do |format|
    format.html {redirect_to login_path, notice: "You have been logged out"}
May 29, 2014 - (v4.0.2)
1 thank

:hidden_field_id was replaced with :include_id

In order to prevent fields_for from rendering a hidden field to store the ID of the record use

include_id: false

instead of

hidden_field_id: false
May 22, 2014
0 thanks

Original URL Example

# get “/articles?page=2”

request.original_url # => “http://www.example.com/articles?page=2”

May 16, 2014
0 thanks

You can add if: :query_method and unless: :query_method

You can make the callback conditional:

before_save :before_method, if: :needs_before_method?


def needs_before_method?

def before_method
  # .. 
May 6, 2014
0 thanks

How to set request parameters (rails 3.2)

In Rails 3.2, this seems to work to create a TestRequest based on a certain url:

ActionController::TestRequest.new( Rack::MockRequest.env_for("http://something.tld/foo?one=two&three=four") )    
May 5, 2014 - (v4.0.2)
0 thanks

Example Regex format matching

for phone and email

validates_format_of :phone, with: /\A(\d{10}|\(?\d{3}\)?[-. ]\d{3}[-.]\d{4})\z/
validates_format_of :email, with: /\A[\w]([^@\s,;]+)@(([\w-]+\.)+(com|edu|org|net|gov|mil|biz|info))\z/i
May 5, 2014 - (v3.2.13)
0 thanks

another way

Perhaps a more efficient way:

def create
  @post = Post.new(post_params)
  if @post.save
    redirect_to @post, notice: "The post #{@post.title} was added to the system."
    render action: 'new'

where post_params is:


def post_params
  params.require(:post).permit(..attributes to permit..)
May 4, 2014
0 thanks


In regards to @aamer’s comment on including the password salt this is a bad idea. `ActiveSupport::MessageVerifier` is NOT encrypted so:

verifier = ActiveSupport::MessageVerifier.new('secret')
id = 'id'
salt = 'salt'
verifier.generate("#{id}-#{salt}") # "BAhJIgxpZC1zYWx0BjoGRVQ=--c880254708d18ce4a686bcd96a25cf0d2117e1e0"

Base64.decode64(token.split("--").first) # "...id-salt..."

Note how the salt and id are both exposed! Instead a different token (reset_passowrd_token) should be used.

May 1, 2014
0 thanks

Passing an array of keys to exclude.

Use the “*” before passing the array in. For example:

PARAMS_TO_SCRUB = [ :created_at, :updated, :id, :format ]

params.except!( *PARAMS_TO_SCRUB )
April 24, 2014 - (<= v4.0.2)
1 thank

First example's output is incorrect

Everything except the initially html_safe input should be escaped in the output.

The output of the first example should be:

# => "<p>foo</p>&lt;br /&gt;&lt;p&gt;bar&lt;/p&gt;"
April 23, 2014
0 thanks

Does not symbolize hashes in nested arrays

If you have a nested structure containing arrays of hashes, you still need to do that on your own, eg.

module SymbolizeHelper
  def symbolize_recursive(hash)
    {}.tap do |h|
      hash.each { |key, value| h[key.to_sym] = map_value(value) }

  def map_value(thing)
    case thing
    when Hash
    when Array
      thing.map { |v| map_value(v) }

Or, if you want to get really fancy with Ruby refinements (YMMV), one could do

module SymbolizeHelper
  extend self

  def symbolize_recursive(hash)
    {}.tap do |h|
      hash.each { |key, value| h[key.to_sym] = transform(value) }


  def transform(thing)
    case thing
    when Hash; symbolize_recursive(thing)
    when Array; thing.map { |v| transform(v) }
    else; thing

  refine Hash do
    def deep_symbolize_keys

And later say

using SymbolizeHelper # augmented Hash#deep_symbolize_keys is now available
April 21, 2014 - (>= v4.0.2)
0 thanks
April 19, 2014
0 thanks

Compatible with old docs

Library is moved, so old library documentation is compatible http://apidock.com/rails/v3.0.9/ActionController/Streaming/send_file

April 14, 2014 - (v3.2.13)
0 thanks
April 9, 2014 - (>= v4.0.2)
0 thanks

Requires inheritance of ActionController::Metal

The example code will not work unless class inherits from ActionController::Metal (to get functioning controller) or at least AbstractController:Base.

April 1, 2014
1 thank

Sometimes, you need the "Oxford comma"

Re: Gramatical error


We invited the strippers, JFK, and Stalin.

versus the appositive phrase:

We invited the strippers, JFK and Stalin.

(Really, you need to see the comic to appreciate the difference.)

April 1, 2014
0 thanks

Grammatical error

Hi - not sure where I would submit this so just putting here. My apologies if not in the right place.

default: “, and ” - this is grammatically wrong. There should be no comma with the last and.


[‘one’, ‘two’, ‘three’].to_sentence

should give: “one, two and three”

There is no ‘ .… , and ’ which is considered grammatically incorrect I feel. The ‘and’ does it’s job in the English language quite well by joining the two words it’s in between.

Thank you.

March 27, 2014
0 thanks

Update for Rails 4

In the example

select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })

It can be updated to

select("post", "person_id", Person.pluck(:name, :id), { include_blank: true })
March 10, 2014
0 thanks

gives a parameter

As a note, you can use it like this:

after_save {|instance|


it will pass in the instance being saved.

March 7, 2014
0 thanks

form_for with :path route

Similar to danwich’s note, if you specify a route using the :path option

resource :posts, path: 'articles'

then the form_for tag must specify the :url option

form_for(@post), url: post_path(@post)