Recent notes
RSS feedOrder with hash parameters only in ActiveRecord >= 4.0
If you use order with hash parameters on AR3 versions it wont work.
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?
Ordering on associations
For ordering on the attribute of an associated model you have to include it:
Package.includes(:package_size).order("package_sizes.sort_order")
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 ] } )
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!" end end
and
class BookController < SystemController def index end end
And calling important_method from Book’s index view will raise an NoMethodError.
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 } end
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.
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.
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
Note:
a.try(&:doesnt_exist) #=> Raises NoMethodError
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.
callbacks
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
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.
Deprecated in favour of []
In Rails 3+
company.errors[:name]
In Rails 2.3 and below:
company.errors.on(:name)
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 "#{msg}".html_safe end end flash.discard response end
so in your controller,
def get_data_and_update_div @user_details=User.get_details if @user_details.nil? flash.now[:error]="Add your details and then submit" format.js { render 'shared/error_messages'} end
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 %> </div>
include respond_to in your controller action only if there are multiple formats of that view
consider this
def index @users=User.get_users respond_to do |format| format.html format.json format.js end end
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 @users=User.get_users end
So if your action is being called both by BOTH ajax,non-ajax call,its good to use respond_to.
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"%> $("admin_panel").show(); $("user_panel").hide(); <% elsif params[:controller]== "user"%> $("admin_panel").hide(); $("user_panel").show(); <% elsif params[:controller]== "video"%> $("admin_panel").hide(); $("user_panel").hide(); $("video_panel").show(); <% else %> $("admin_panel").hide(); $("user_panel").hide(); $("video_panel").hide(); <%end%>
simple use
Examples
<%= @user.created_at.to_date.to_formatted_s(:long_ordinal)%> => July 5th, 2014
OR
<%=@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
Using fontawesome icons inside link_to
<%= link_to (‘<i class=“fa fa-thumbs-up fa-lg”> </i>’).html_safe, vote_path(@image)%>
in this way you can use thumbs-up icon instead of usual text such as “like” in link_to
4.0.2 support
Where did this go in 4.0.2?
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 end resources :photos do resources :comments end
end
<%= form_for([:admin, @comment], :url => polymorphic_path([:admin, @commentable, @comment])) do |form| %>
Note : @commentable = find_commentable
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 end end
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 end
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”
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).
Reject If
reject_if: proc { |attributes| attributes[‘name’].blank? } Has saved me after an 3 hours of google search. Thanks
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 @current_user_session.destroy respond_with @current_user_session do |format| format.html {redirect_to login_path, notice: "You have been logged out"} end end
Original URL Example
# get “/articles?page=2”
request.original_url # => “http://www.example.com/articles?page=2”