Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 277 lines (221 sloc) 8.023 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
rails 3 rollback migration
===========================
rake db:rollback

through capistrano
namespace :db do
   desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
   task :rollback => :environment do
     step = ENV['STEP'] ? ENV['STEP'].to_i : 1
     version = ActiveRecord::Migrator.current_version - step
     ActiveRecord::Migrator.migrate('db/migrate/', version)
   end
 end

sendmail configure
================
config.action_mailer.raise_delivery_errors = true
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.sendmail_settings = {
    :location => '/usr/sbin/sendmail',
    :arguments => '-i -t'
}

Helper to print numbers as ordinals (1st, 2nd, 3rd...)
======================================

def number_to_ordinal(num)
  num = num.to_i
  if (10...20)===num
    "#{num}th"
  else
    g = %w{ th st nd rd th th th th th th }
    a = num.to_s
    c=a[-1..-1].to_i
    a + g[c]
  end
end

number_to_ordinal(12) => "12th"
number_to_ordinal(7) => "7th"

uninitialized constant UsersController
============================
Add following line into routes
map.resources :users, :controller => 'user'

simple form submission
==================
<% form_for @users do |f| %>
<%= f.text_field :name %><br/>
<%= f.text_field :email %><br/>
<%= f.text_field :country %><br/>
<%= f.submit 'save' %>
<% end %>

simple create method
================
def new
    @users = User.new
  end

  def create
    @users = User.new(params[:user])
    #render :text => params.inspect and return
    if @users.save
      redirect_to root_path
      flash[:notice]="saved successfully"
    end
  end

render
==========
render :action => "action"
render :action => "action", :layout => "layoutname"
render :file => "filepath"
render :file => "filepath", :use_full_path => false
render :inline => "<%= 'hello' %>"
render :inline => "<%= 'hello' %>", :locals => { :name => "value" }
render :inline => "<%= 'hello' %>", :type => :rxml
render :layout => "layoutname"
render :nothing => true
render :nothing => true, :status => 401
render :partial => "item"
render :partial => "item", :collection => items
render :partial => "item", :locals => { :name => "value" }
render :partial => "item", :object => object
render :partial => "item", :status => 500
render :text => "text to render..."
render :text => "text to render...", :layout => "layoutname"
render :text => "text to render...", :layout => true
render :text => "text to render...", :status => 401
render_component :action => "index"
render_component :controller => "items"
render_component :controller => "items", :action => "index"
verify :only => [:], :method => :post, :render => {:status => 500, :text => "use HTTP-POST"}
verify :only => [:], :session => :user, :params => :id, :redirect_to => {:action => 'index'}

pagination numbers adding in typus admin
===============================
app\views\admin\helpers\_pagination.html.erb

<div class="pagination">

  <% if @items.prev? %>
    <%= link_to "&larr; " + _("Previous"), params.merge(:page => @items.prev.number, :anchor => @options[:anchor]) %>
  <% else %>
    <span class="disabled"><%= "&larr; " + _("Previous") %></span>
  <% end %>

  <% last_page = 0 -%>

  <% build_pagination(@pager) do |n| -%>
    <% if @items.number == n -%>
      <span class="current"><%= n %></span>
    <% else -%>
      <%= "..." if last_page + 1 < n %>
      <%= link_to n, params.merge(:page => n, :anchor => @options[:anchor]) %>
    <% end -%>
    <% last_page = n -%>

  <% end -%>

  <% if @items.next? %>
    <%= link_to _("Next") + " &rarr;", params.merge(:page => @items.next.number, :anchor => @options[:anchor]) %>
  <% else %>
    <span class="disabled"><%= _("Next") + " &rarr;" %></span>
  <% end %>

</div>

app\helpers\admin\master_helper.rb

##
  # Simple and clean pagination links
  #
  def build_pagination(pager, options = {})

    options[:link_to_current_page] ||= true
    options[:always_show_anchors] ||= true

    # Calculate the window start and end pages
    options[:padding] ||= 2
    options[:padding] = options[:padding] < 0 ? 0 : options[:padding]

    page = params[:page].blank? ? 1 : params[:page].to_i
    current_page = pager.page(page)

    first = pager.first.number <= (current_page.number - options[:padding]) && pager.last.number >= (current_page.number - options[:padding]) ? current_page.number - options[:padding] : 1
    last = pager.first.number <= (current_page.number + options[:padding]) && pager.last.number >= (current_page.number + options[:padding]) ? current_page.number + options[:padding] : pager.last.number

    returning(String.new) do |html|
      # Print start page if anchors are enabled
      html << yield(1) if options[:always_show_anchors] and not first == 1
      # Print window pages
      first.upto(last) do |page|
        (current_page.number == page && !options[:link_to_current_page]) ? html << page.to_s : html << (yield(page)).to_s
      end
      # Print end page if anchors are enabled
      html << yield(pager.last.number).to_s if options[:always_show_anchors] and not last == pager.last.number
    end

  end

How to change reCAPTCHA theme
===========================

 <script type="text/javascript">
 var RecaptchaOptions = {
    theme : '<theme name here>'
 };
 </script>

Rails Ajax Image Uploading Made Simple with jQuery
=======================================
replace below in views,

<% remote_form_for(:image_form, :url => { :controller => "blogs", :action => :create_asset }, :html => { :method => :post, :id => 'uploadForm', :multipart => true }) do |f| %>
 Upload a file: <%= f.file_field :uploaded_data %>
<% end %>

place below code into script,

$('#uploadForm input').change(function(){
 $(this).parent().ajaxSubmit({
  beforeSubmit: function(a,f,o) {
   o.dataType = 'json';
  },
  complete: function(XMLHttpRequest, textStatus) {
    // For example, if you have an image elemtn with id "my_image", then
    $('#my_image').attr('src', XMLHttpRequest.responseText);
  },
 });
});

then action should be like,
@image = Image.new(params[:image_form])
@image.save

Now image will upload without page refresh.

How do I handle date objects in ruby on rails forms?
=======================================
<%= date_select("show", "date", :default => Date.today,
    :order => [:month, :day, :year], :start_year => Date.today.year,
    :end_year => Date.today.year + 3) %>

undefined local variable or method `version_requirements’ for # (NameError)
======================================================
Ruby on Rails suggested inserting following code between bootstrap and initialize section of enviroment.rb.

if Gem::VERSION >= "1.3.6"
module Rails
class GemDependency
def requirement
r = super
(r == Gem::Requirement.default) ? nil : r
end
end
end
end

[or]

$ gem install rubygems-update -v='1.4.2'
$ gem uninstall rubygems-update -v='1.5.0'
$ update_rubygems

rails3 mysql2 adapter error: 'gem install activerecord-mysql2-adapter'
==================================================================
In GemFile minor change

gem 'mysql2' to gem 'mysql2', '< 0.3'

and bundle install it.

created_at and created_on
=========================

created_at

created_at and updated_at are dates and times

created_on

created_on and updated_on are dates only

Rails, rendering partial via JS on after page load
===================================================
show.html.erb

<div id="weather"></div>
weather.js.erb

$( "#weather" ).html( "<%= escape_javascript(render( :partial => 'weather' )) %>");
weather.html.erb

<%= Time.now %> # For brevity. This actually does more.
Controller

def weather

  slow_api_request

  respond_to do |format|
    format.js {render :layout => false}
  end
end

You should simply add an ajax call. Assuming you're using jQuery, just add this kind of scripts in your view:

$.ajax({
  type: "GET",
  url: "<%= url_for your_path %>" ,
  success: function(data){
    //if ever there is something more to do (there is also an error handler)
  }
});
Something went wrong with that request. Please try again.