Notes posted to Ruby on Rails

RSS feed
October 28, 2014
0 thanks

facing issue in create table (errno: 150)

I am trying to create table by writing the following code:

create_table :sam_server_user_audit do | t | t.column :user_id, :string, :limit => 100, :null => false t.column :user_type, :string, :limit => 20, :null => false t.column :status, :string, :limit => 20, :null => false t.column :created_at, :datetime, :null => false end

which generates:

CREATE TABLE `sam_server_user_audit` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `user_id` varchar(100) NOT NULL, `user_type` varchar(20) NOT NULL, `status` varchar(20) NOT NULL, `created_at` datetime NOT NULL, FOREIGN KEY (user_id) REFERENCES users (id)) ENGINE=InnoDB CHARACTER SET `utf8`

here It is adding a foreign key user_id automatically.

How can I avoid that?

October 28, 2014
2 thanks

Ordering on associations

For ordering on the attribute of an associated model you have to include it:

October 1, 2014
0 thanks

Preselecting options

To preselect options, pass in the selected options in the options hash:

{ :selected => [ selected_option_1, selected__option_2, ... ] }

Code example

grouped_collection_select(:city, :country_id, @continents, :countries, :name, :id, :name, { :selected => [1, 5, 6 ] } )
September 18, 2014 - (<= v4.0.2)
0 thanks

Only in ApplicationController

Seems like we can use helper_method only in ApplicationController. Even if we will create child controller, methods that will be created in child and listed in child’s helper_method will not be accessible from the view.

For example, we have

class SystemController < ApplicationController
 def important_method
   "I am important!"


class BookController < SystemController
 def index

And calling important_method from Book’s index view will raise an NoMethodError.

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