you are here: codestackercodes [RSS] → tag rails [RSS]

Creating SQL inserts from Rails

cc = CourseEnrollmentEmailCcUser.new(id: 1, couse_enrollment_email_id: 1)

puts cc.class.arel_table.create_insert.tap { |im|
  im.insert(cc.send(:arel_attributes_with_values_for_create, cc.attribute_names)) 
}.to_sql

how to use number_to_currency in controller

include ActionView::Helpers::NumberHelper

submit a form with a link

<!-- view -->
<%= form_for(@category) do |f| %>
	<!-- fields... -->
	<%= link_to 'Submit', '#', :class => 'submit_me' %>
<% end %>

<!-- javascript --> 
$('.submit_me').click(function() {
  $(this).parent().submit();
  return false;
});

rails 3 validates method

validates :login, :presence => true, :length => {:minimum => 4}, :uniqueness => true, :format => { :with => /[A-Za-z0-9]+/ }

# :presence => true

# :uniqueness => true

# :numericality => true

# :length => { :minimum => 0, maximum => 2000 }

# :format => { :with => /.*/ }

# :format => { :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i } # email format

# :format => { :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix } # url format

# :inclusion => { :in => [1,2,3] }

# :exclusion => { :in => [1,2,3] }

# :acceptance => true

# :confirmation => true

rails 3 url validation

# paste in your model


validates :url, :presence => true, :format => { :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix }

activerecord without rails

require 'active_record'

ActiveRecord::Base.establish_connection(:adapter => 'mysql2', :host => 'localhost', :user => 'root', :password => 'mypass', :database => 'mydatabase')

class User < ActiveRecord::Base ; end

puts User.count
#=> 9

check avaliability

# controller

def check_availability
  render :update do |page|
    if User.find(:first, :conditions => { :login => params[:user][:login] })
      page[:login_instant_feedback].replace_html 'Not available'
    end
  end
end

# view

link_to_remote 'check availability', { :url => { :action => 'check_availability' }, :before => $('login_instant_feedback').update('checking...'); new Effect.Appear('login_instant_feedback');" }

rails inspired helpers in javascript

var link_to = function (text, url, options) {
  var link = document.createElement('a');
  link.textContent = text;
  link.setAttribute('href', url);

  for (option in options) {
    link.setAttribute(option, options[option]);
  }

  return link;
};

var image_tag = function (alt, src, options) {
  var image = document.createElement('img');
  image.setAttribute('alt', alt);
  image.setAttribute('src', src);

  for (option in options) {
    image.setAttribute(option, options[option]);
  }

  return image;
};

link_to("Google", "http://google.com", { id: 321, title: "Google" });

image_tag("Google", "http://www.google.com/images/logos/ps_logo2.png", { id: "logo", title: "Google's Logo" });

find or create

class Category < ActiveRecord::Base
  validates_uniqueness_of :name

  def self.create_or_find_by_name(name)
    create!(:name => name) rescue find_by_name(name)
  end
end

flash_messages helper method to rails 3

def flash_messages 
  %w(notice warning error).each do |msg| 
    concat content_tag(:div, content_tag(:p, flash[msg.to_sym]), :class => msg) unless flash[msg.to_sym].blank? 
  end 
end

rails 3 two lines install

gem install i18n tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler

gem install rails --pre

i18n in labels

rails 2.3.4 doen't have i18n support in labels

http://lawrencesong.net/2009/04/i18n-label-in-rails-monkey-patch/

module ActionView 
  module Helpers 
    class InstanceTag 
      def to_label_tag_with_i18n(text = nil, options = {}) 
        text ||= object.class.human_attribute_name(method_name) if object.class.respond_to?(:human_attribute_name) 
 
        to_label_tag_without_i18n(text, options) 
      end 
 
      alias_method_chain :to_label_tag, :i18n 
    end 
  end 
end

paperclip refresh all images

run this task

rake paperclip:refresh class=MyClass

use default_scope to set up default find conditions such as order

class MyModel < ActiveRecord::Base
  default_scope :order => 'created_at desc'
end

humanized attributes

class User < ActiveRecord::Base

  HUMANIZED_ATTRIBUTES = {
    :email => "E-mail address"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

end

paperclip ie validation

validates_attachment_content_type :image,
  :content_type => [
    'image/jpeg',
    'image/pjpeg', # for progressive jpeg (IE mine-type for regular jpeg) 

    'image/png',
    'image/x-png', # IE mine-type for PNG

    'image/gif'
]

finding duplicates entries

having example in rails. from: http://blog.grayproductions.net/articles/five_activerecord_tips

duplicates = User.find( :all,
  :select     => "email, COUNT(email) AS duplicate_count",
  :conditions => "email IS NOT NULL AND email != ''",
  :group      => "email HAVING duplicate_count > 1"
)

hirb example

to install:
gem install cldwalker-hirb --source http://gems.github.com

>> require 'hirb'
=> []
>> Hirb.enable
=> nil
>> Exam.find(:all, :limit => 5)
+----+----------+----------+----------+----------+---------+----------+------+
| id | title    | exam     | creat... | updat... | user_id | categ... | hits |
+----+----------+----------+----------+----------+---------+----------+------+
| 1  | Simul... | Simul... | 2009-... | 2009-... | 1       | 1        | 152  |
| 2  | Simul... | Simul... | 2009-... | 2009-... | 1       | 1        | 143  |
| 3  | Espec... | Espec... | 2009-... | 2009-... | 1       | 1        | 1089 |
| 4  | Espec... | Espec... | 2009-... | 2009-... | 1       | 1        | 80   |
| 5  | Espec... | Espec... | 2009-... | 2009-... | 1       | 1        | 40   |
+----+----------+----------+----------+----------+---------+----------+------+
5 rows in set
>>

listing files in a directory with rails

@files = Dir.glob("public/files/*")

for file in @files
    puts file
end

email regex

validates_format_of :email, 
:with => /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/, 
:message => "is invalid" 
Displaying Code 1 - 20 of 49 in total