About ruby on rails, hackintosh, iphone3g and etc.

Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Thursday, December 3, 2009

Enable Multiple Buttons in a Form in Rails

Sometimes we need more than one button in the form. To do so in Ruby On Rails, we have to do the following:

Create a method in the controller to accept the form input
e.g

def approve_form
case params[:submit]
when "Approve"
redirect_to :action=>"approve"
return
when "Reject"
redirect_to :action=>"reject"
return
end
end


in your form, do this

Friday, May 8, 2009

Using ISAPI Rewrite on Rails App with IIS and Mongrel as Windows Service

In setting up a multiple production environment in a single server, IIS alone cannot do the redirection of url nicely. When a RAILS app runs in IIS, it requires port number and to redirect domain name to the particular port number, ISAPI Rewrite can help. Below are some sample of how to redirect a hostname to the port required.

RewriteCond %{HTTP:Host} ^(?:www\.)?domain name\.biz$
RewriteRule (.*) http://www.domain name.biz:3000$1 [R=301,L]

RewriteCond %{HTTP:Host} ^(?:www\.)?another domain name\.com$
RewriteRule (.*) http://www.another domain name.com:3001$1 [R=301,L]

Updated: 27th May 2009
Possible to do URL masking by using rewrite proxy

RewriteCond %{HTTP:Host} ^(?:www\.)?another domain name\.com$
RewriteProxy (.*) http://localhost:4002$1

Note: it will map to localhost:4002 and transparent to user as the url shown is www.anotherdomainname.com. You can point multiple domain name to a single web app.

To get this done:
1. Install ISAPI Rewrite.
2. Copy and replace domain name to your own domain name in ISAPI rewrite.
3. If you have more than one domain pointing to the same server, just add below the first domain.

Thursday, April 30, 2009

Calendar Date Select for Ruby on Rails

CalendarDateSelect is semi-light-weight (about ~20k of javascript/css) and easy to use (but gets even lighter with bundle-fu)! It takes full advantage of the prototype.js library, resulting in less code, but maintaining a great deal of functionality.

Some of it's capabilities:

can pick a date, or a date-time, or a date with an optional time, as a popup selector or an embedded calendar!
speaks several different formats
is easy to localize
is extensible. Calendar Date Select doesn't do everything under the sun (which is a good thing), but you can build on top of it.
Installation / Usage

Install the calendar_date_select gem
sudo gem install calendar_date_select
Add a gem dependency to your rails project (in environment.rb)
config.gem "calendar_date_select"
Then, restart/start your rails project. All necessary files will be copied to your public folder.
Now include this at the top of your layout: (you'll also need to include prototype, if you haven't already!)
<%= calendar_date_select_includes "red" # or "blue", or "silver", or nil for the default! %>
# (if you want more control, you can get a list of stylesheets / javascripts via calendar_date_select_javascripts and calendar_date_select_stylesheets)
See the Demo for various uses of CalendarDateSelect.

Wednesday, April 29, 2009

Date Calculation in Rails

>> Date.new( 2008, 1, 1 ).to_time.advance( :months => 1 )
=> Fri Feb 01 00:00:00 +0000 2008


>> Date.new( 2008, 2, 1 ).to_time.advance( :months => 1 )

=> Sat Mar 01 00:00:00 +0000 2008

>> Date.new( 2008, 1, 1 ).to_time + 1.month
=> Thu Jan 31 00:00:00 +0000 2008

Extracted from here:
http://roninonrails.blogspot.com/2008/01/beware-of-rails-date-arithmetic.html

Tuesday, April 28, 2009

Get Month Name in Rails

To get month name as constants, do the following

require 'date'

for i in (1..12)
@month = Date::MONTHNAMES[i]
end

Saturday, March 7, 2009

Attachment_fu Installation

Installing Attachment_fu plugin steps as follows:

1. Install Freeimage plugin for image processing:

sudo port selfupdate

sudo port install freeimage (link)

MacPorts installation notes can be obtained from here.


2. Install ImageScience

sudo gem install -y image_science


3. Install Attachment_fu


script/plugin install http://svn.techno-weenie.net/projects/plugins/attachment_fu/

Wednesday, March 4, 2009

Mongrel_rails

To use mongrel_rails in production, you need to create a service to run in your Windows Server.

Navigate to the directory where rails app are located.

Replace (service name) including bracket with your service name .
Here is the command:

Install service:
mongrel_rails service::install -N (service name) -e (environment. e.g. production) -p (port to be used)

Remove the service:
mongrel_rails service::remove -N (service name)

That's all. Then you can configure lightttpd to point to the mongrel web app.

To start the service from command line:
net start (service name)

Thursday, February 26, 2009

SQL SUM() in Rails

In Rails, Active Record support many types of calculations. It saves us from executing SELECT SUM(x) using the query. Everything can be shorten down one line of code.

Example:
To find sum of all items in a location:

Item.sum('location_id', :conditions =>['location_id = ?', location.id])

Similar to avg and others. See ActiveRecord API for more info.

Sunday, February 22, 2009

Install github on Mac OSX

Github is very useful for Ruby on Rails programmers. A lot of plugins and sample codes available. To use git in Mac OSX, you will need to install github by the following link:


Download the installer for OS X. That's all.

Open Flash Chart

OpenFlashChart is an excellent flash based charting tool. It has been ported to Ruby. A very useful tutorial by pullmonkey.com http://pullmonkey.com/2008/7/25/using-a-database-to-populate-an-open-flash-chart-graph.

To install the plugin:

script/plugin install git://github.com/pullmonkey/open_flash_chart.git

Then, copy swfobject.js from the plugin's assets/ directory. 

That's all. For coding steps, please refer to the link above.

"Code below extracted from pullmonkey.com"

open_flash_chart_object()

Usage:

This method returns only the graph html:
@graph = open_flash_chart_object(....)

Arguments

  • width (required)
  • height (required)
  • url (required)
  • use_swfobject (optional and defaults to true)
  • base (optional and defaults to "/")
  • swf_file_name (optional and defaults to "open-flash-chart.swf")

Wednesday, February 4, 2009

Changes in production database

After deploying rails into production environment, I do need to do updates on database tables and others as user requirements added on. Here is the method to do migration on production databases.

rake db:migrate RAILS_ENV="production"


Rails Validate More than 1 Primary Key

In Ruby on Rails, you can specify your model class to validate uniqueness of multiple columns (multiple primary key). Here is the command:

validates_uniqueness of :email, :scope => :name

if you want to validate uniqueness of a triplet or more

validates_uniqueness of :first_attr, :scope => [ :second_attr,
:third_attr ... ]

Monday, February 2, 2009

Connecting Rails to MS SQL Server 2000

The fasted method to connect Rails to MS SQL Server 2000 is using ODBC. Install gem plug-in using the command below:

gem update --system

gem install activerecord-sqlserver-adapter --source=http://gems.rubyonrails.org

Next steps are very important. It is very common for Windows database developer but not if you are from other platform like OSX or Linux.

Create DSN (Data Source Name) in Administrative Tools, Data Sources (ODBC).




Important!!! Make sure the default database is set to the database you wanted to use. Else it will default to Masters database.

Remember the Data Source Name.

Next is to configure your database.yml file in Rails config directory

Here is the settings:

production:
  adapter: sqlserver
  mode: odbc
  dsn: SMSdb
  username: USERNAME
  password: PASSWORD

Try using the rake migration command in my earlier post.

For DSN less configuration (means does not need to create a DSN in Data Sources (ODBC)).

database.yml settings:

development:
    adapter: sqlserver
    mode: odbc
    dsn: DRIVER=/opt/local/lib/libtdsodbc.so;TDS_Version=8.0;SERVER=sqlserver.com;DATABASE=DBNAME;Port=14330;uid=dbusername;pwd=dbpassword;

Friday, January 30, 2009

Starting Rails in Production Environment

Once moving the database to production environment, next is to run rails in production environment. There are a few commands like:

mongrel_rails start -e production

(start mongrel server in production environment)

rake RAILS_ENV=production

Or for console testing:

ruby script/console production

Moving Rails to Production Database

After development (better during development) of rails application, it is good to move/try out the production database environment. To move to production database (e.g. from sqlite to mysql), firstly need to modify the database.yml file in /config directory of rails app.

database.yml

production:
adapter: mysql
database:
username: root
password:
socket: /path/to/your/mysql.sock

Change the database name to your database name. For mysql, create a schema that match the schema name. Enter the username and password, try to avoid root. 

In mysql terminal, create a dababase schema using this command:

mysqladmin -u root -p create

Create a user for this schema and use the username. Leave socket field as it is.

Save database.yml and execute the command below:

rake db:schema:load RAILS_ENV=production

There maybe error if mysql gem plugin is not installed, this can be resolved by this command:

gem install mysql

References:

Thursday, January 22, 2009

Using id after update/create command for rails

In rails, there is a useful method as to capture the id of a record upon successful creation of the record in database.
Example code:

@contact = Contact.new(params[:contact])

respond_to do |format|
if @contact.save

Listing above shows typical execution of creating a row in rails model. Upon save, rails will automatically populate the @contact class with the id generated from database. (@contact.id)

So we can continue to use the following:

@contact = Contact.new(params[:contact])

respond_to do |format|
if @contact.save
#create empty contact details with only contact id
@contact_details = ContactDetails.new()
@contact_details.contact_id = @contact.id
@contact_details.save

@contact.id can be used to populate foreign key of @contact_details.

Wednesday, January 7, 2009

Using rake db:migrate

In Ruby on Rails, it is very to add new version of database tables or columns. It has built-in support in by using this command:

rake db:migrate

To revert back to the earlier version of database structures, just add VERSION= xxx to the back of the command. It becomes:

rake db:migrate VERSION=20090103162017

(this number "20090103162017" is the version number of the migration files generated by rake db:migrate. It is so simple.

else you can use

rake db:rollback

(this will rollback the last migration)