Recent notes

RSS feed
September 12, 2014
0 thanks

Be careful with .select

With 999 people in the table:

Person.select('person.firstname').find_in_batches do |group|
  group.each { |person| puts person.firstname }

Will work properly.

But with 1001 people in the table, this will raise “Primary key not included in the custom select clause”. It’s a bit of a time bomb. If you’re writing tests for methods that use this, you won’t see a failure unless you’ve tested with more than records than the default batch size.

August 25, 2014 - (v3.1.0 - v3.2.13)
1 thank

This method does not correctly dup arrays

Watch out because this method does not correctly dup arrays values.

The bug can be reproduced with the following code:

hash = { 'a' => [1,2,3,4] }
dup  = hash.deep_dup
dup['a'].object_id == hash['a'].object_id # should return true

Rails 4 version does not have this issue because it is completely different implementation.

August 21, 2014 - (v4.0.2)
3 thanks

In Rails 4 it DOES return nil, even if the object you try from isn't nil

The try method does not raise a NoMethodError if you call a method that doesn’t exist on an object.

a = Article.new

a.try(:author) #=> #<Author ...>

nil.try(:doesnt_exist) #=> nil

a.try(:doesnt_exist) #=> nil


a.try(&:doesnt_exist) #=> Raises NoMethodError
August 19, 2014 - (v3.0.9 - v3.1.0)
0 thanks

False query string parameters removed

This method is used in url_for (therefore in redirects as well).

If you pass a query string parameter to a url route that is false, before Rails 3.1, the generate method would reject it.

This causes issues on the redirected page if you are depending on the param to be have a specific value.

In Rails 3.2 they remove params.reject! {|k,v| !v.to_param} altogether.

So every single param you send is a string.

August 19, 2014
0 thanks


As a note, AFAICT, this skips “validations” but does still run all callbacks still [like after_save, etc.] So if you’re looking for something that just updates see here: http://stackoverflow.com/a/7243777/32453

August 13, 2014 - (>= v4.0.2)
0 thanks

Non-existent key semantics changed.

For Rails 4.0, the behaviour of this has changed when you pass a key that isn’t in the hash.

3.2 (undocumented):

{ a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1, :x => nil}

4.0 (as per docs):

{ a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}

The 4.0 behaviour is now consistent with the behaviour of slice, the 3.2 behaviour was not.

August 8, 2014 - (>= v3.1.0)
0 thanks

Removed in Rails 3.1 and up

Use this instead

August 8, 2014 - (v3.0.0 - v4.0.2)
0 thanks

Deprecated in favour of []

In Rails 3+


In Rails 2.3 and below:

August 5, 2014
0 thanks

Handling flash for ajax calls

This is helper method which can be easily used to handle flash for ajax calls

##call it in your js.erb
def flash_display
response = ""
flash.each do |name, msg|
	msg=msg+"<button type='button' class='close' title='hide' data- dismiss='alert'><i class='fa-times-circle-o fa pull-right'></i></button>".html_safe
  response = response + 
  content_tag(:div, msg, :id => "flash_# {name}",:class=>"alert alert-danger") do 

so in your controller,

def get_data_and_update_div
 if @user_details.nil?
   flash.now[:error]="Add your details and then submit"
   format.js { render   'shared/error_messages'}

in error_messages.js.erb

$('#flash_messages').html("<%= escape_javascript raw(flash_display) %>");

in view file

<div id="flash_messages">
  <% if flash[:error] %>
   <%= content_tag :div, flash['value'], :id =>"flash_error" %>
 <% end %>
August 5, 2014
0 thanks

include respond_to in your controller action only if there are multiple formats of that view

consider this

def index
  respond_to do |format|

is good if you have a call to users/index by both

<%= link_to ("Show users",user_path)%>
##will render users/index.html.erb
===Also same call but with ajax
<%= link_to ("Show users",user_path,remote=>true)%>
 ##will render users/index.js.erb..handled by respond_to   block
===Also same call but with json
<%= link_to ("Show users",user_path,remote=>true,:format=>json)%>
##will render users/index.json.erb..handled by respond_to   block.

But if you have just first one,so remove respond_to block as you are sure that you only need index.html.erb ALWAYS

def index

So if your action is being called both by BOTH ajax,non-ajax call,its good to use respond_to.

August 5, 2014
0 thanks

Using render to handle ajax call using same js.erb(DRY)

Suppose your application have many pages using some common view and is updated using ajax,so you can use a single js in multiple views to avoid duplication

format.js { render 'profile/show_user_details' }

And in my profiles/show_user_details.js i can use conditions instead of creating regular partials

<% if params[:controller]== "dashboard"%>
<% elsif params[:controller]== "user"%>
<% elsif params[:controller]== "video"%>
<% else %>
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
2 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)
2 thanks

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;"