by sandipransing
Rails routes can be customized as your own routes with parameters but first you should understand how routes behaves.
Adding dynamic parameters to routes
Here exact parameters are matched to route and presence of each parameter is mandatory in order to construct urls. blank parameter will raise RoutingError exception.
Exact matched named route declared as -
match ':a/:b/:c', :to => 'home#index', :as => :q
now go to the rails console -
ruby-1.9.3-head :005 > app.q_url(:a, :b, :c)
=> "http://www.example.com/a/b/c"
ruby-1.9.3-head :006 > app.q_url(:a, :b, '')
ActionController::RoutingError: No route matches {:controller=>"home", :a=>:a, :b=>:b, :c=>""}
Bound parameters to named routes
If you are too sure that certain parameter can be blank then you can define it as optional parameter inside route -
match ':a/:b(/:c)', :to => 'home#index', :as => :q
rails console
ruby-1.9.3-head :010 > app.q_url(:a, :b, '')
=> "http://www.example.com/a/b?c="
ruby-1.9.3-head :011 > app.q_url(:a, :b)
=> "http://www.example.com/a/b"
Read More…
by sandipransing
CSV (comma separated values) files are frequently used to import/export data.
In rails 3, FasterCSV comes as default and below is the way to upload csv files inside rails applications. The code below will also show you how to generate csv in memory, parse on csv data, skip header, iterate over records, save records inside db, export upload error file and many more.
First, View to upload file
= form_tag upload_url, :multipart => true do
%label{:for => "file"} File to Upload
= file_field_tag "file"
= submit_tag
Assume upload_url maps to import action of customers controller
Controller code
class CustomersController < ApplicationController
[...]
def import
if request.post? && params[:file].present?
infile = params[:file].read
n, errs = 0, []
CSV.parse(infile) do |row|
n += 1
# SKIP: header i.e. first row OR blank row
next if n == 1 or row.join.blank?
# build_from_csv method will map customer attributes &
# build new customer record
customer = Customer.build_from_csv(row)
# Save upon valid
# otherwise collect error records to export
if customer.valid?
customer.save
else
errs << row
end
end
# Export Error file for later upload upon correction
if errs.any?
errFile ="errors_#{Date.today.strftime('%d%b%y')}.csv"
errs.insert(0, Customer.csv_header)
errCSV = CSV.generate do |csv|
errs.each {|row| csv << row}
end
send_data errCSV,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{errFile}.csv"
else
flash[:notice] = I18n.t('customer.import.success')
redirect_to import_url #GET
end
end
end
[...]
end
Customer model
class Customer < ActiveRecord::Base
scope :active, where(:active => true)
scope :latest, order('created_at desc')
def self.csv_header
"First Name,Last Name,Email,Phone,Mobile, Address, FAX, City".split(',')
end
def self.build_from_csv(row)
# find existing customer from email or create new
cust = find_or_initialize_by_email(row[2])
cust.attributes ={:first_name => row[0],
:last_name => row[1],
:email => row[3],
:phone => row[4],
:mobile => row[5],
:address => row[6],
:fax => row[7],
:city => row[8]}
return cust
end
def to_csv
[first_name, last_name, email, phone, mobile, address, fax, city]
end
end
Export customer records in CSV format
Below code loads customer records from database then generate csv_data inside memory and
exports data to browser using send_data method.
Note: As we are not writing on file system hence code can easily work heroku.
def export
# CRITERIA : to select customer records
#=> Customer.active.latest.limit(100)
custs = Customer.limit(10)
filename ="customers_#{Date.today.strftime('%d%b%y')}"
csv_data = FasterCSV.generate do |csv|
csv << Customer.csv_header
custs.each do |c|
csv << c.to_csv
end
end
send_data csv_data,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{filename}.csv"
end
Read More…
by sandipransing
mongoid document supports array as field. array field in mongoid document is a ruby array but its quite complex to manage array field in rails forms.
After lot of google and reading comments from stack-overflow at last i felt helpless. Finally after doing research on rails form helper object(form_for, fields_for) am pleased to get it working as expected :)
In below example, product can have multiple categories
class Product
CATEGORIES = %w(Apparel Media Software Sports Agri Education)
include Mongoid::Document
field :name, :type => String
field :categories, :type => Array
end
Here is form code
= form_for(@product) do |f|
= f.text_field :name
- Product::CATEGORIES.each do |category|
= f.check_box :categories, :name => "product[categories][]", category
Here is products controller code
class ProductsController < ApplicationController
before_filter :load_product, :only => [:new, :create]
[...]
# We don't need new action to be defined
def create
@product.attributes = params[:product]
# Here we need to reject blank categories
@product.categories.reject!(&:blank?)
if @product.save
flash[:notice] = I18n.t('product.create.success')
redirect_to(:action => :index)
else
render :action => :new
end
end
[...]
private
def load_product
@product = Product.new
end
end
Read More…
by sandipransing
twitter-bootstrap is pluggable css suit provided by twitter.
To know more about how to get started on it click here
Below post will help you out in getting started bootstrap css with rails app.
One need to add below files to helpers directory. MainForm can be used as base version of form builder and can be overriden for its subsequent use inside other custom form builders.
1. MainForm
# app/helpers/main_form.rb
class MainForm < ActionView::Helpers::FormBuilder # NestedForm::Builder
CSS = {
:label => 'label-control',
:hint => 'hint',
:hint_ptr => 'hint-pointer',
:error => 'help-inline',
:field_error => 'error',
:main_class => 'clearfix'
}
FIELDS = %w(radio_button check_box text_field text_area password_field select file_field collection_select email_field date_select)
def main_class(error=nil)
return CSS[:main_class] unless error
[CSS[:main_class], CSS[:field_error]].join(' ')
end
def required(name)
object.class.validators_on(name).map(&:class).include?(ActiveModel::Validations::PresenceValidator) rescue nil
end
def cancel(options={})
link = options.fetch(:return, "/")
@template.content_tag(:a, "Cancel", :href => link, :class => "btn_form button np_cancel_btn #{options[:class]}")
end
def submit(value="Save", options={})
options[:class] = "send_form_btn #{options[:class]}"
super
end
def label_class
{:class => CSS[:label]}
end
def label_tag(attribute, arg)
# Incase its a mandatory field, the '*' is added to the field.
txt = arg[:label] && arg[:label].to_s || attribute.to_s.titleize
txt<< '*' if(arg[:required] || required(attribute)) && arg[:required] != false
label(attribute, txt, label_class)
end
def error_tag(method_name, attribute)
errs = field_error(method_name, attribute)
@template.content_tag(:span, errs.first, :class => CSS[:error]) if errs.present?
end
def field_error(method_name, attribute)
return if @object && @object.errors.blank?
return @object.errors[attribute] if method_name != 'file_field'
@object.errors["#{attribute.to_s}_file_name"] | @object.errors["#{attribute.to_s}_file_size"] | @object.errors["#{attribute.to_s}_content_type"]
end
def hint_tag(txt)
hintPtr = @template.content_tag(:span, '', :class => CSS[:hint_ptr])
hintT = @template.content_tag(:span, txt + hintPtr, {:class => CSS[:hint]}, false)
end
def spinner_tag
@template.image_tag('spinner.gif', :class => :spinner,:id => :spinner)
end
end
ZeroForm is custom form builder which is inherited from main_form and its going to be actually used inside forms. Feel free to make custom form related changes inside this
ZeroForm
cat app/helpers/zero_form.rb
class ZeroForm < MainForm
# Overridden label_class here as we dont need class to be applied
def label_class
{}
end
def self.create_tagged_field(method_name)
define_method(method_name) do |attribute, *args|
arg = args.last && args.last.is_a?(Hash) && args.last || {}
# Bypass form-builder and do your own custom stuff!
return super(attribute, *args) if arg[:skip] && args.last.delete(:skip)
errT = error_tag(method_name, attribute)
labelT = label_tag(attribute, arg)
mainT = super(attribute, *args)
baseT = @template.content_tag(:div, mainT + errT)
hintT = hint_tag(arg[:hint]) if arg[:hint]
spinnerT = spinner_tag if arg[:spinner]
allT = labelT + baseT + spinnerT + hintT
@template.content_tag(:div, allT, :class => main_class(errT))
end
end
FIELDS.each do |name|
create_tagged_field(name)
end
end
In order to use Nested Forms you need to extend MainForm with NestedForm Builder
Integrate NestedForm with FormBuilder
class MainForm < NestedForm::Builder
end
View Form
= form_for @address ||= Address.new, :builder => ZeroForm do |f|
= f.text_field :street_address
= f.text_area :detail_address, :rows => 2
= f.text_field :city
= f.select :state, %w(US IN AUS UK UKRAINE)
= f.submit 'Save & Continue', :class => 'btn primary'
= link_to 'Skip »', '#'
To know more on twitter-bootstrap pagination in rails click here
Read More…
by sandipransing
How to get collection of models inside your application. Certainly there are many ways to do it.
Lets have a look at different ways starting from worst -
Get table names inside database and then iterating over to get model name
@models = ActiveRecord::Base.connection.tables.collect{|t| t.underscore.singularize.camelize}
#=> ["AdhearsionAudit", "AudioLog", "AuditDetail","TinyPrint", "TinyVideo", "UnknownCall", "UserAudit", "User"]
Select those with associated class
@models.delete_if{|m| m.constantize rescue true}
Load models dir
@models = Dir['app/models/*.rb'].map {|f| File.basename(f, '.*').camelize.constantize.name }
Select ActiveRecord::Base extended class only
@models.reject!{|m| m.constantize.superclass != ActiveRecord::Base }
Get Active Record subclasses
# make sure relevant models are loaded otherwise
# require them prior
# Dir.glob(RAILS_ROOT + '/app/models/*.rb').each { |file| require file }
class A < ActiveRecord::Base
end
class B < A
end
ActiveRecord::Base.send(:subclasses).collect(&:name)
#=> [...., A]
How to get Inherited models too
class A < ActiveRecord::Base
end
class B < A
end
ActiveRecord::Base.descendants.collect(&:name)
#=> [...., A, B]
Below is more elegant solution provide by Vincent-robert over stack overflow which recursively looks for subsequent descendent's of class and gives you list from all over application
class Class
def extend?(klass)
not superclass.nil? and ( superclass == klass or superclass.extend? klass )
end
end
def models
Module.constants.select do |constant_name|
constant = eval constant_name
if not constant.nil? and constant.is_a? Class and constant.extend? ActiveRecord::Base
constant
end
end
end
Read More…
by sandipransing
Stripe is simple website payment solution and its very easy to easy setup
It currently supports only in US and seems to be very popular compared to other payment gateways because of its api & pricing
Stripe API provides -
1. charge (regular payments)
2. subscription (recurring payments)
3. managing customers (via stripe_customer_token)
What you need to do ?
Create a stripe account by providing email address and password. There after go to the manage account page to obtain stripe public & api keys.
Rails Integration
# Gemfile
gem stripe
# config/initializers/stripe.rb
Stripe.api_key = "rGaNWsIG3Gy6zvXB8wv4rEcizJp6XjF5"
STRIPE_PUBLIC_KEY = "vk_BcSyS2qPWdT5SdrwkQg0vTSyhZgqN"
# app/views/layouts/application.html.haml
= javascript_include_tag 'https://js.stripe.com/v1/'
= tag :meta, :name => 'stripe-key', :content => STRIPE_PUBLIC_KEY
Payment Form
# app/views/payments/new.html.haml
#stripe_error
%noscript JavaScript is not enabled and is required for this form. First enable it in your web browser settings.
= form_for @payment ||= Payment.new, :html => {:id => :payForm} do |p|
= p.hidden_field :stripe_card_token
.field
= p.text_field :amount
.credit_card_form
%h3.title
Enter Credit Card
- if @payment.stripe_card_token.present?
Credit card has been provided.
- else
.field
= label_tag :card_number, "Credit Card Number"
= text_field_tag :card_number, nil, name: nil
.field
= label_tag :card_code, "Security Code (CVV)"
= text_field_tag :card_code, nil, name: nil
.field
= label_tag :card_month, "Expiry Date"
= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"}
= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"}
Javascript Code
# app/views/payments/new.js
var payment;
jQuery(function() {
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
return payment.setupForm();
});
payment = {
setupForm: function() {
$('.head').click(function() {
$(this).css('disabled', true);
if($('#payment_stripe_card_token').val()){
$('#payForm').submit();
}
else{
payment.processCard();
}
});
},
processCard: function() {
var card;
card = {
number: $('#card_number').val(),
cvc: $('#card_code').val(),
expMonth: $('#card_month').val(),
expYear: $('#card_year').val()
};
return Stripe.createToken(card, payment.handleStripeResponse);
},
handleStripeResponse: function(status, response) {
if (status === 200) {
$('#payment_stripe_card_token').val(response.id)
$('#stripe_error').remove();
$('#payForm').submit();
} else {
$('#stripe_error').addClass('error').text(response.error.message);
$('.head').css('disabled', false);
}
}
};
Generate & Migrate Payment Model
rails g model payment status:string amount:float email:string transaction_number:string
rake db:migrate
Payment Model
# app/models/payment.rb
class Payment < ActiveRecord::Base
PROCESSING, FAILED, SUCCESS = 1, 2, 3
attr_accessible :stripe_card_token
validates :amount, :stripe_card_token, :presence => true, :numericality => { :greater_than => 0 }
def purchase
self.status = PROCESSING
customer = Stripe::Customer.create(description:email, card: stripe_card_token)
# OPTIONAL: save customer token for further reference
stripe_customer_token = customer.id
# Charge
charge = Stripe::Charge.create(
:amount => amount * 100, # $15.00 this time
:currency => "usd",
:customer => stripe_customer_token
)
if charge.paid
self.transaction_num = charge.id
self.status = SUCCESS
else
self.status = FAILED
end
return self
rescue Exception => e
errors.add :base, "There was a problem with your credit card."
self.status = FAILED
return self
end
end
Payments Controller
# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
def create
@payment = Payment.new(params[:payment])
if @payment.valid? && @payment.purchase
flash[:notice] = 'Thanks for Purchase!'
redirect_to root_url
else
render :action => :new
end
end
end
Read More…
by sandipransing
railroady is UML class diagram generator for rails.
First you need to install `graphviz` pkg in order to have `dot` , `neato` commands available
group :development, :test do
gem railroady
end
Run below command to generate MVC diagrams
bundle install
rake diagram:all
Individual diagram generation
Model Diagram
railroady -M | dot -Tpng > models.png
Controller Diagram
railroady -C | dot -Tpng > controllers.png
AASM Diagram
railroady -A | dot -Tpng > aasm.png
Commands
-M, --models Generate models diagram
-C, --controllers Generate controllers diagram
-A, --aasm Generate "acts as state machine" diagram
Options
# Common options
-b, --brief Generate compact diagram
(no attributes nor methods)
-s, --specify file1[,fileN] Specify given files only for the diagram
(can take a glob pattern)
-e, --exclude file1[,fileN] Exclude given files
(can take a glob pattern)
-i, --inheritance Include inheritance relations
-l, --label Add a label with diagram information
(type, date, migration, version)
-o, --output FILE Write diagram to file FILE
-v, --verbose Enable verbose output
(produce messages to STDOUT)
Models diagram options:
-a, --all Include all models
(not only ActiveRecord::Base derived)
--all-columns Show all columns
(not just content columns)
--hide-magic Hide magic field names
--hide-types Hide attributes type
-j, --join Concentrate edges
-m, --modules Include modules
-p, --plugins-models Include plugins models
-t, --transitive Include transitive associations
(through inheritance)
Controllers diagram options:
--hide-public Hide public methods
--hide-protected Hide protected methods
--hide-private Hide private methods
Other Options
-h, --help Show this message
--version Show version and copyright
Read More…
by sandipransing
active_admin is the good way to provide rails administrative interface.
It provides front-end db administration and its customizable too :)
# Gemfile
gem 'activeadmin'
gem 'sass-rails'
gem "meta_search", '>= 1.1.0.pre'
Bundle install, generate config & migrate db
bundle install
rails g active_admin:install
rake db:migrate
Config
# config/initializers/active_admin.rb
ActiveAdmin.setup do |config|
config.site_title = "Web Site :: Admin Panel"
config.site_title_link = "/"
config.default_namespace = :siteadmin
config.authentication_method = :authenticate_admin_user!
config.current_user_method = :current_admin_user
config.logout_link_method = :delete
end
Registering new resource
rails generate active_admin:resource category
Customization
# app/admin/categories.rb
ActiveAdmin.register Category do
scope :published
form do |f|
f.inputs do
f.input :name, :label => 'Name'
f.input :for_type, :label => "Category Type"
end
f.buttons
end
end
Adding Dashboard
ActiveAdmin::Dashboards.build do
section "Recent Categories" do
table_for Category.published.recent.limit(2) do
column :name do |c|
link_to c.name, [:admin, c]
end
column :created_at
end
strong { link_to "View All Categories", admin_categories_path }
end
end
Read More…
by sandipransing
Twitter bootstrap is css toolkit for rapid front-end UI development.
To get will-paginate working with bootstrap css we need to override default pagination link renderer.
Using Bootstrap-sass for rails 3
# Gemfile
gem 'sass-rails'
gem 'bootstrap-sass'
# app/assets/stylesheets/application.css.sass
// Place all the styles related to the home controller here.
// They will automatically be included in application.css.
// You can use Sass (SCSS) here: http://sass-lang.com/
//= require bootstrap
Add WillPaginate LinkRenderer to intitializer
# config/initializers/will_paginate.rb
module WillPaginate
module ActiveRecord
module RelationMethods
alias_method :per, :per_page
alias_method :num_pages, :total_pages
alias_method :total_count, :count
end
end
module ActionView
def will_paginate(collection = nil, options = {})
options[:inner_window] ||= 0
options[:outer_window] ||= 0
options[:class] ||= 'pagination pull-left'
options[:renderer] ||= BootstrapLinkRenderer
super.try :html_safe
end
class BootstrapLinkRenderer < LinkRenderer
protected
def html_container(html)
tag :div, tag(:ul, html), container_attributes
end
def page_number(page)
tag :li, link(page, page, :rel => rel_value(page)), :class => ('active' if page == current_page)
end
def previous_or_next_page(page, text, classname)
tag :li, link(text, page || 'javascript:void(0)'), :class => [classname[0..3], classname, ('disabled' unless page)].join(' ')
end
def gap
tag :li, link(super, 'javascript:void(0)'), :class => 'disabled'
end
end
end
end
Read More…
by sandipransing
jQuery datepicker plugin is used to display inline calendar popup that eases user input experience while entering date/time fields. Calendar can be easily binded to any html DOM element. To Apply different styles download css from here
# Gemfile
gem "jquery-rails"
# console
bundle install
# app/assets/javascripts/application.js.coffee
//= require jquery
//= require jquery_ujs
//= require jquery-ui
# app/views/layouts/application.html.haml
= stylesheet_link_tag "application"
= stylesheet_link_tag "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css"
= javascript_include_tag "application"
Before using timepicker download jquery-ui-timepicker js
wget http://trentrichardson.com/examples/timepicker/js/jquery-ui-timepicker-addon.js app/assets/javascripts/
Add timepcker js to application.js.coffee
//= require jquery-ui-timepicker-addon
## inside views
# app/views/users/_form.html.haml
= form_for @user ||= User.new do |f|
= f.text_field :birth_date, :id => 'birthDate'
= f.text_field :birth_time, :id => 'birthTime'
= f.text_field :exam_on, :id => 'examOn'
:javascript
$(document).ready(function() {
$("#birthDate").datepicker();
$("#birthTime").timepicker();
$("#examOn").datetimepicker();
$('#ui-datepicker-div').removeClass('ui-helper-hidden-accessible')
# customizations
$('#birth_date').datepicker({ dateFormat: 'dd-mm-yy' });
$('#birth_date').datepicker({ disabled: true });
$("#examOn").datetimepicker({ ampm: true });
$("#examOn").datetimepicker({ timeFormat: 'h:m', separator: ' @ ' });
Read More…
by sandipransing
Heroku is readonly file system hence write operations can only be done inside tmp directory.
Asset compilation on heroku can be handled in different ways
#1. compiling locally and placing inside assets directory
RAILS_ENV=production bundle exec rake assets:precompile
#2. It compiles assets while slug compiles
#3. Run time asset compilation
# It compiles assets for every rails request if it notifies assets got modified
# config/application.rb
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.prefix = Rails.root.join('tmp/assets').to_s
# config/environments/production.rb
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
Note: write operation made inside tmp directory can not make any guarantee of being persisted hence be careful while using.
Read More…
by sandipransing
Devise handles authentication, authorization part inside rails application quite easily and its customizable too. One can always customize default devise configurations.
This Post will show how to manage multiple resources (like admin, staff, employees, guests etc.) through devise and STI with individual registrations process but login section will be the same for all.
# Gemfile
gem 'devise'
# console
bundle install
rails g devise_install
rails g devise User
rake db:migrate
rake routes
# User model
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable, :confirmable and :activatable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation
end
## Single Table Inheritance
# Admin model
class Admin < User
end
# Staff
class Staff < User
end
# Employee
class Employee < User
end
# Guest
class Guest < User
end
# routes
devise_for :users, :skip => :registrations
devise_for :admins, :skip => :sessions
devise_for :staffs, :skip => :sessions
devise_for :employees, :skip => :sessions
devise_for :guests, :skip => :sessions
# customizing default login/logout routes, views, actions
devise_for :users, :controller => {:sessions => 'sessions'}, :skip => [:sessions, :registrations] do
delete '/logout', :to => 'sessions#destroy', :as => :destroy_user_session
get '/login', :to => 'sessions#new', :as => :new_user_session
post '/login', :to => 'sessions#create', :as => :user_session
end
# app/controllers/sessions_controller
class SessionsController < Devise::SessionsController
end
## overriding default after sign in path
# app/controller/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :account_url
def account_url
return new_user_session_url unless user_signed_in?
case current_user.class.name
when 'Customer'
edit_customer_registration_url
when 'Admin'
edit_home_page_section_url
else
root_url
end if user_signed_in?
end
end
# app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
def after_sign_in_path_for(resource)
stored_location_for(resource) || account_url
end
end
## Changing default login field email to username
# config/initializers/devise.rb
config.authentication_keys = [ :username ]
# app/models/user.rb
validates :username, :presence => true,
:uniqueness => {:allow_blank => true},
:format => {:with => /^\w+[\w\s:?']+$/i, :allow_blank => true}
def email_required?
false
end
Adding devise authentication and authorization helper methods for above resources.
read more here
Read More…
by sandipransing
Upload image via paperclip via passing URL instead of file upload
# Consider Print instance with image as file attachment
class Print < ActiveRecord::Base
has_attached_file :image
def upload_image(url)
begin
io = open(URI.escape(url))
if io
def io.original_filename; base_uri.path.split('/').last; end
io.original_filename.blank? ? nil : io
p.image = io
end
p.save(false)
rescue Exception => e
logger.info "EXCEPTION# #{e.message}"
end
end
end
Text code from console
p = Print.new
url = "http://ocdevel.com/sites/ocdevel.com/files/images/rails.png"
p.upload_image(url)
Read More…
by sandipransing
Rails 3 Installation
sudo gem install rails -v3.0.4
postgres as db installation<>br/
$ sudo apt-get install postgresql
Rails 3 App with postgres as database
$ rails new pg -d postgres
bundle installation
It will install dependency gems & postgres adapter for db connection
bundle install
Here by default 'postgres' database user gets created while installation but i recommend to create new db user with name same as of system user owning project directory permissions.
User owning file permission can be found using
ls -l pg
drwxr-xr-x 7 sandip sandip 4096 2011-02-23 15:38 app
drwxr-xr-x 5 sandip sandip 4096 2011-02-23 18:14 config
-rw-r--r-- 1 sandip sandip 152 2011-02-23 15:38 config.ru
...
Default 'postgres' database user gets created while installation
## Snap of database.yml
development:
adapter: postgresql
encoding: unicode
database: pg_development
username: sandip
pool: 5
Create new database user
pg $ sudo su postgres
pg $ createuser sandip
Shall the new role be a superuser? (y/n) y
pg $ exit
exit
Create a first development database:
pg $ psql template1
Welcome to psql 8.4.6, the PostgreSQL interactive terminal.
...
template1=# \l
List of databases
Name | Owner | Encoding
-----------+----------+----------
postgres | postgres | UTF8
template0 | postgres | UTF8
template1 | postgres | UTF8
(3 rows)
template1=# CREATE DATABASE pg_development;
CREATE DATABASE
template1=# \l
List of databases
Name | Owner | Encoding
-------------------+----------+----------
postgres | postgres | UTF8
pg_development | sandip | UTF8
template0 | postgres | UTF8
template1 | postgres | UTF8
(4 rows)
template1=# \q
Start rails server
pg $ rails s
Getting hands on postgres terminal
1. Login onto terminal
psql -U DB_USERNAME -d DB_NAME -W DB_PASSWORD
2. List databases
\l
3. Display tables
\dt
4. Exit from terminal
\q
Read More…
by sandipransing
Here are the simple steps to be followed while upgrading rails version to use.
# Install rails version 1. gem install rails -v == gem install rails 2.3.3
# Upgrade environment.rb for new version 2. RAILS_GEM_VERSION = '' unless defined? RAILS_GEM_VERSION == RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION
# Upgrade necessary files for the new version 3. rake rails:upadte
# Start server 4. /script/server
Thats, it !
Read More…
|