Showing posts with label Rails Basics. Show all posts
Showing posts with label Rails Basics. Show all posts

Sunday, September 6, 2009

Rails Basics : link_to

It is an almost Rails convention that you should use Ruby code rather than HTML to create links as a mater of style and flexibility via routes.rb

link_to is an example of a Rails function  for html generation and is typically used to add site-wide navigation. For example,

   <%= link_to('Home',       { :action = 'index'}) %> |
   <%= link_to('About Us', { :action ='about'}) %>

You may be interested to note that curly braces are optional in hashes where they are the final argument to a function as follows :-

   <%= link_to('About Us',:action ='about') %>

How does one not link to a page that is currently displayed ?

   <%= link_to_unless_current('Home',       { :action = 'index'}) %> |
   <%= link_to_unless_current('About Us', { :action ='about'}) %>

Are there other related link_to functions ?

Rails adheres to a naming convention whereby a group of related functions have related names, usually of the form original_function_name and original_function_name_with_modification

Let's check to the Rails API via the Rails API Tab in Aptana Radrails or  at http://api.rubyonrails.org and this is what you should find

  • link_to
  • link_to_if
  • link_to_remote
  • link_to_unless
  • link_to_unless_current
How to display an image inside a link_to

<%= link_to image_tag("about.gif", :border=>0), :action => 'about' %>

Wednesday, September 2, 2009

Rail Basics : What happens when you script/generate ?

chee@ibm4linux:~/workspace/crm4test$ script/generate

Usage: script/generate generator [options] [args]
Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.
General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)
    -g, --git                        Modify files with git. (Note: git must be in path)


Installed Generators
  Plugins (vendor/plugins): authenticated, roles
  Builtin: controller, helper, integration_test, mailer, metal, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration

More are available at http://wiki.rubyonrails.org/rails/pages/AvailableGenerators
  1. Download, for example, login_generator.zip
  2. Unzip to directory /home/chee/.rails/generators/login
     to use the generator with all your Rails apps
     or to /home/chee/workspace/crm4test/lib/generators/login
     to use with this app only.
  3. Run generate with no arguments for usage information
       script/generate login

Generator gems are also available:
  1. gem search -r generator
  2. gem install login_generator
  3. script/generate login

Rails Basics : What happens when you script/generate model ?

chee@ibm4linux:~/workspace/crm4test$ script/generate model

Usage: script/generate model ModelName [field:type, field:type]
Options:
        --skip-timestamps            Don't add timestamps to the migration file for this model
        --skip-migration             Don't generate a migration file for this model
        --skip-fixture               Don't generation a fixture file for this model
Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.
General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)
    -g, --git                        Modify files with git. (Note: git must be in path)

Description:
    Stubs out a new model. Pass the model name, either CamelCased or
    under_scored, and an optional list of attribute pairs as arguments.

    Attribute pairs are column_name:sql_type arguments specifying the
    model's attributes. Timestamps are added by default, so you don't have to
    specify them by hand as 'created_at:datetime updated_at:datetime'.

    You don't have to think up every attribute up front, but it helps to
    sketch out a few so you can start working with the model immediately.

    This generates a model class in app/models, a unit test in test/unit,
    a test fixture in test/fixtures/singular_name.yml, and a migration in
    db/migrate.

Examples:
    `./script/generate model account`

        creates an Account model, test, fixture, and migration:
            Model:      app/models/account.rb
            Test:       test/unit/account_test.rb
            Fixtures:   test/fixtures/accounts.yml
            Migration:  db/migrate/XXX_add_accounts.rb

    `./script/generate model post title:string body:text published:boolean`

        creates a Post model with a string title, text body, and published flag.

Sunday, August 30, 2009

Rail Basics : What happens when you script/generate controller ?

What do you think will happen if you script/generate controller  ?

Why wonder, just do it :-)

If you are using Ubuntu 9.04, just open a Terminal Window and cd to the root of your Rails applications and type script/generate controller -- as follows :-

chee@ibm4linux:~/workspace/crm2009$ script/generate controller

After pressing Enter, this is what you will see.

Usage: script/generate controller ControllerName [options]
Rails Info:
    -v, --version                    Show the Rails version number and quit.
    -h, --help                       Show this help message and quit.
General Options:
    -p, --pretend                    Run but do not make any changes.
    -f, --force                      Overwrite files that already exist.
    -s, --skip                       Skip files that already exist.
    -q, --quiet                      Suppress normal output.
    -t, --backtrace                  Debugging: show backtrace on errors.
    -c, --svn                        Modify files with subversion. (Note: svn must be in path)
    -g, --git                        Modify files with git. (Note: git must be in path)

Description:
    Stubs out a new controller and its views. Pass the controller name, either
    CamelCased or under_scored, and a list of views as arguments.

    To create a controller within a module, specify the controller name as a
    path like 'parent_module/controller_name'.

    This generates a controller class in app/controllers, view templates in
    app/views/controller_name, a helper class in app/helpers, a functional
    test suite in test/functional and a helper test suite in test/unit/helpers.

Example:
    `./script/generate controller CreditCard open debit credit close`

    Credit card controller with URLs like /credit_card/debit.
        Controller:      app/controllers/credit_card_controller.rb
        Functional Test: test/functional/credit_card_controller_test.rb
        Views:           app/views/credit_card/debit.html.erb [...]
        Helper:          app/helpers/credit_card_helper.rb
        Helper Test:     test/unit/helpers/credit_card_helper_test.rb

Modules Example:
    `./script/generate controller 'admin/credit_card' suspend late_fee`

    Credit card admin controller with URLs /admin/credit_card/suspend.
        Controller:      app/controllers/admin/credit_card_controller.rb
        Functional Test: test/functional/admin/credit_card_controller_test.rb
        Views:           app/views/admin/credit_card/debit.html.erb [...]
        Helper:          app/helpers/admin/credit_card_helper.rb
        Helper Test:     test/unit/helpers/admin/credit_card_helper_test.rb

Rails Basics : How to Install a Plugin from the Command Line ?

Although Aptana Radrails and other Rails IDE usually have a Rails Plugin Tab or its equivalent, I personally feel that it easier and more flexible to do so using the Command Line.

To do so in Ubuntu 9.04, click Applications/Accessories/Terminal to open a terminal window and cd to the root of your Rails Project as follows :-

chee@ibm4linux:~$ cd workspace
chee@ibm4linux:~/workspace$ cd crm2009

chee@ibm4linux:~/workspace/crm2009$ script/plugin install

To discover the various options available in script/plugin

chee@ibm4linux:~/workspace/crm2009$ script/plugin --
Unknown command:
Usage: plugin [OPTIONS] command
Rails plugin manager.
GENERAL OPTIONS
  -r, --root=DIR                   Set an explicit rails app directory.
                                   Default: /home/chee/workspace/crm2009
  -s, --source=URL1,URL2           Use the specified plugin repositories instead of the defaults.
  -v, --verbose                    Turn on verbose output.
  -h, --help                       Show this help message.
COMMANDS
  discover   Discover plugin repositories.
  list       List available plugins.
  install    Install plugin(s) from known repositories or URLs.
  update     Update installed plugins.
  remove     Uninstall plugins.
  source     Add a plugin source repository.
  unsource   Remove a plugin repository.
  sources    List currently configured plugin repositories.

EXAMPLES
  Install a plugin:
    plugin install continuous_builder

  Install a plugin from a subversion URL:
    plugin install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder

  Install a plugin from a git URL:
    plugin install git://github.com/SomeGuy/my_awesome_plugin.git

  Install a plugin and add a svn:externals entry to vendor/plugins
    plugin install -x continuous_builder

  List all available plugins:
    plugin list

  List plugins in the specified repository:
    plugin list --source=http://dev.rubyonrails.com/svn/rails/plugins/

  Discover and prompt to add new repositories:
    plugin discover

  Discover new repositories but just list them, don't add anything:
    plugin discover -l

  Add a new repository to the source list:
    plugin source http://dev.rubyonrails.com/svn/rails/plugins/

  Remove a repository from the source list:
    plugin unsource http://dev.rubyonrails.com/svn/rails/plugins/

  Show currently configured repositories:
    plugin sources

Saturday, August 29, 2009

Rails Basics : What is a Model ?

What is a Model ?

The Model is the 'M' in the MVC (Model/Views/Controller) concept integral to a Rails application.

Models should :-
  • Constitute most of your application codes. 
  • Provide  a persistent storage mechanism to your database
  • Define all business logic
In a nutshell, Models should be the brains that operate on your application's database, determine and change the state of other objects and co-ordinate the overall business logic of your applications.

Conventions for Models

Model classes in Rails are all inherited from the ActiveRecord base class ActiveRecord::Base and map one-to-one to a table in your database.

Residing in the app/models directory, Models should following the following convention :-
  • Only one class per file
  • Class name should be singular and camel-cased eg.Customer or BillNo
  • Corresponding table name should be lowercased, plural and underscored eg. customers or bill_nos
  • Corresponding table must have an auto-incrementing integer field called id
  • Column names shoudl also be lowercased
  • Model filename should be lowercased and underscored version of the class name eg. customer.rb or bill_no.rb
To represent the relationship between tables and columns in your application, ActiveRecord provides the following set of methods called associations :-
  • has_many represents a zero-to-many relationship between the Parent & Child Class
  • belongs_to is the reciprocal child method to parent has_many method
  • has_one  is like a belongs_to and represents a one-to-one relationship in your database


More to come...

Friday, August 28, 2009

Rails Basics : What is a Controller ?

What is a Controller ?

The Controller is an integral component of the MVC (Model/View/Controller) concept that is central to Rails. Controllers are normal Ruby classes that inherit from ActionController:Base or more frequently the generated ApplicationController Class

Controllers have public action methods that can be called from the dispatcher as well as their own protected and private methods. Typically, action methods follow this pattern :-
  • Manipulate the domain model in some way
  • Refers to the response format requested by the user
  • Generate a response in the correct form by rendering a view template
Controllers are more closely linked to Views than Models in that you can work on a Model in your application before even creating a Controller. That is why script/generate controller will also automatically create helpers and views folders but not a model folder as follows :-

script/generate controller Concepts
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/concepts
      exists  test/functional/
      exists  test/unit/helpers/
      create  app/controllers/concepts_controller.rb
      create  test/functional/concepts_controller_test.rb
      create  app/helpers/concepts_helper.rb
      create  test/unit/helpers/concepts_helper_test.rb

As such, you should remove all Business Logic from your Controllers and put in the corresponding Model.

So what does the Controllers in your Rails application  do ?

Well, your controllers are only responsible for mapping between URLs, co-ordinating with your Models and your Views and channeling back to a HTTP response. In addition, it may do Access Control as well.

Basically, when someone connects to your Rails Application via an URL, they are ly asking your Application to execute a Controller Action. Typically, action methods follow this pattern :-
  • Interact with the domain model in some way such as selecting, inserting or updating data based on incoming parameters or using one or more classes form the app/model directory
  • Generate a response by rendering a view template with the same name as the action method
Controller Conventions
As you may be aware, Rails works magically so long as you adhere to the all important concepl of Convention over Configuration. In this respect Controller Conventions include :-

a)  The Controller's class name should be camel cased and pluralised and be followed by the word controller. eg.CustomersControllers or BillNosControllers

b)  Similar to Models, the controller filename should be lowercased and underscored versions of the class name. eg. customers_controllers.rb or bill_nos_controllers.rb

c)  An action is a Public Method of a controller class. For example
  • index
  • show
  • new
  • create
  • edit
  • update
  • destroy 
BTW, the above-mentioned actions are RESTful Rails actions. Each one of these methods connects the data in the Model layer to what you allow the user to see.

What is fascinating is that unless explicitly told to do , Rails will render the views with the same name as the actions!

How to remove a controller and all previously generated files ?

chee@ibm4linux:~/workspace/crm2009$ script/destroy controller concepts
          rm  test/unit/helpers/concepts_helper_test.rb
          rm  app/helpers/concepts_helper.rb
          rm  test/functional/concepts_controller_test.rb
          rm  app/controllers/concepts_controller.rb
    notempty  test/unit/helpers
    notempty  test/unit
    notempty  test
    notempty  test/functional
    notempty  test
       rmdir  app/views/concepts
    notempty  app/views
    notempty  app
    notempty  app/helpers
    notempty  app
    notempty  app/controllers
    notempty  app
chee@ibm4linux:~/workspace/crm2009$

Wednesday, October 31, 2007

Rails Basics : Useful Helpers

In developing the e-CRM, I have found the following helper methods very useful :-

a) Hardcoded select list

def severity_form_column (record, name)
select_tag name, options_for_select(%w(Show-stopper Severe Nice-to-have Customisation Trivial), record.severity)
end

b) TextArea for edit/create

def blog_form_column(record, input_name) text_area_tag('record[blog]', @record.blog, :size=>"80x30")
end

c) checkbox for edit/create

def active_form_column(record, input_name)
check_box :record, :active, :name => input_name
end

e) checkbox for list
def active_column(record)
check_box_tag 'active', 1, record.active?, { :disabled => true }
end

f) date display for list
def bill_date_column(record)
if record.bill_date.nil?
record.bill_date= '-' #''&nbsp'
else
record.bill_date.strftime("%d/%m/%y")
end
end

g) Customising Rails date format

def mydate_form_column(record, input_name)
date_select(:record, :mydate :order =>
[:day, :month, :year], :start_year => 1970, :end_year => 2000)
end

h) Controlling Text Field Size

def name_form_column(record, input_name)
text_field_tag('record[name]', @record.name, { :autocomplete => "off", :size => 40, :class => 'text-input'})
end

Saturday, October 27, 2007

Rails Basics : All about Validations

Irrespective of languages, frameworks and platforms, one cannot run away from providing validations to data input. How does Ruby on Rails do it ?

To be precise, Active Record, an integral part of RoR, provides validation support as follows :-

a) validates_acceptance_of(attribute, :message => "message", :accept => "1")
b) validates_confirmation_of(attribute, :message => "message")

c) validates_exclusion_of(attribute, :in => enumerable_object, :message => "message")
d) validates_inclusion_of(attribute, :in => enumerable_object, :message => "message")

e) validates_length_of(attribute, :maximum => max, :allow_nil => true, :message => "message")

f) validates_length_of(attribute, :minimum => min, :message => "message")
g) validates_length_of(attribute, :in => range, :message => "message")

h) validates_numericality_of(value, :message => "message")

i) validates_presence_of(attributes, :message => "message")

j) validates_size_of(attribute, :maximum => max, :message => "message")
k) validates_size_of(attribute, :minimum => min, :message => "message")
l) validates_size_of(attribute, :in => range, :message => "message")

m) validates_uniqueness_of(attributes, :message => "message", :scope => "condition")
n) validates_uniqueness_of(attributes, :message => "message", :scope => "condition")

Saturday, October 20, 2007

Rails Basics : I am a newbie, what should I read ?

Just like thousands of experienced programmers who have flocked to Ruby after seeing the incredible demo on how easy it was to create a Ruby on Rails Applications, I started on RoR and after a short while, I hit a road block :-(

What did I do next ?

Consistent with I did when I started by programming career via Clipper, I went to my favourite bookshop and bought all the Rails and Ruby Books available.

What I bought include :-

  1. Dummies Guide to Ruby and Rails
  2. Rails Cookbook
  3. Ruby Cookbook
  4. Rails Solution
  5. Agile Web Development with Rails
  6. Ruby on Rails : Up and Running
  7. Rails Recipes
  8. The Ruby Way : 2nd Edition
  9. Active Record

Updated on 30th August 2009
    Programming Ruby
    The Rails Way
    Rails Space
    Rails for .NET Developers (August, 2009)




Welcome to Rails.. Rails... Rails !

In 1995, I started the popular Clipper...Clipper... Clipper website (no blogs then) which was very popular and linked by virtually every Clipper-related site. When I switched to Windows via Delphi in 1997, I started the Delphi... Delphi... Delphi site. In June 2007, I discovered Ruby on Rails and no prize for guessing what I am gonna name this blog. which I started on 2nd October 2007.

As at 10th June 2010, we have 13,364 unique visitors from more than 84 countries such as Angola, Andorra, Argentina, Australia, Austria, Algeria,Barbados, Bosnia and Herzogovina, Belgium, Brazil, Bulgaria, Bangladesh, Belarus, Bolivia, Chile, Cambodia, Cape Vede, Canada, China, Colombia, Costa Rica, Croatia, Cyprus, Czech Republic, Denmark, Egypt, Estonia, Finland, France, Guadeloupe, Guatemala, Germany, Greece, Hong Kong, Hungary, India, Indonesia, Ireland, Israel, Italy, Japan, Kenya, Korea, Lithuania, Latvia, Malaysia, Mexico, Macao, Netherlands, Nepal, Norway, New Zealand, Oman, Panama, Peru, Poland, Portugal,Paraguay , Philippines, Romania, Russian Federation, Saudi Arabia, Singapore, Spain, Slovakia, Slovenia, Serbia, South Korea, Slovenia, South Africa, Spain, Switzerland, Sri Lanka, Sweden, Taiwan, Thailand, Turkey, United Arab Emirates, Ukraine, USA, UK, Venezuela, Vietnam

CCH
10th June 2010, 19:42