09 Apr 2010

Introduction to Active Scaffold Part I

Active Scaffold, tutorials posted by payal

I originally wrote this article for fifth issue of Rails Magazine. In addition to print version, you can download all issues of Rails Magazine in pdf for free. Not only that, they also allow authors to self-publish their articles on blogs etc. after 30 days of issue release. I hope rails beginners will particularly find this post useful.


In this two-part series, I will trying to explain Active Scaffold from the ground up using a real world example.

Introduction

ActiveScaffold is a rails plugin that generates an ajaxified management interface based on the database tables.  It is an incredibly powerful, configuration-driven framework that automatically provides all CRUD operations. It is easily and highly configurable. Let us have a walkthrough of active scaffold with details on configurability and customization options it provides using a sample application. The demo application which we are going to develop is a management site for a sports club.

Configuration

Here our example is about building an administration panel for a sports club “mysportsclub”. It consists of sports, players, coaches and equipments. There are various kinds of sports in the club. Each player can have membership for any number of sports. Each sport will have one trained coach for guidance and various equipments which will be issued to the players. Let’s begin with the implementation of “mysportsclub”

Let’s setup our rails application “mysportsclub”. Run the following commands:

rails mysportsclub

Install the latest version of the plugin which is compatible with latest stable rails (2.3.x):

script/plugin install git://github.com/activescaffold/active_scaffold.git

Note: Latest active scaffold version works only with rails version higher than 2.2. Also, install render_component plugin since it is now removed from rails 2.3 but used by active scaffold.

Layout:

This is the standard active scaffold layout admin.html.erb:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
   <title>My Sports Club</title>
   <%= javascript_include_tag :defaults %>
   <%= active_scaffold_includes %>
</head>
<body>
   <%= yield %>
</body>
</html>

Model/Migrations:

script\generate model sport name:string description:text coach_id:integer
script\generate model player name:string date:birth_date
script\generate model equipment name:string sport_id:integer
script\generate model coach name:string
script\generate model players_sport player_id:integer sport_id:integer

rake db:migrate

Add the following code to the respective models. This code defines the associations for the various models:

sports.rb

class Sport < ActiveRecord::Base
  belongs_to :coach
  has_many	:equipments, :dependent => :destroy

  has_many	:players_sports, :dependent => :destroy
  has_many	:players, :through	=> :players_sports

  validates_presence_of	:name
  validates_uniqueness_of	:name
end

coach.rb

class Coach < ActiveRecord::Base
  has_one	:sport
  validates_presence_of	:name
end

player.rb

class Player < ActiveRecord::Base
  has_many	:players_sports, :dependent => :destroy
  has_many	:sports, :through	=> :players_sports

  validates_presence_of	:name
end

equipment.rb

class Equipment < ActiveRecord::Base
  belongs_to	:sport
  validates_presence_of	:name
end

players_sport.rb

class PlayersSport < ActiveRecord::Base
  belongs_to	:player
  belongs_to	:sport
end

Note I

Don’t forget to add the plural form of “equipment” as “equipments” in the config/intializers/inflections.rb.

 ActiveSupport::Inflector.inflections do |inflect|
   inflect.plural "equipment", "equipments"
 end

Active Scaffold will throw an exception if we do not define the above inflection rule.  The controller generated for the ‘Equipment’ model will be ‘EquipmentsController’. But since active scaffold generates the controller name automatically using its inbuilt function: “active_scaffold_controller_for(class_name_of_the_model)”. It will not be able to guess the correct controller name and would throw an exception while we try to access the nested equipments:

Controllers:

script\generate controller sports
script\generate controller coaches
script\generate controller equipments
script\generate controller players

Add the following code to your controllers:

sports_contrpller.rb

class SportsController < ApplicationController
  active_scaffold :sport do |config|
    config.columns = [:name, :description, :coach, :equipments]
  end
end

coaches_controller.rb

class CoachesController < ApplicationController
  active_scaffold :coach do |config|
    config.columns = [:name, :sport]
  end
end

players_controller.rb

class PlayersController < ApplicationController
  active_scaffold :player do |config|
    config.columns = [:name]
  end
end

equipments_controller.rb

class EquipmentsController < ApplicationController
  active_scaffold :equipment	do |config|
    config.columns = [:name, :sport]
  end
end

players_sports_controller.rb

class PlayersSportsController < ApplicationController
  active_scaffold :players_sport do |config|
    config.columns = [:sport, :player]
  end
end

routes.rb

map.root :controller => 'sports', :action => 'index'

map.resources :sports, :active_scaffold => true
map.resources :players, :active_scaffold => true
map.resources :players_sports, :active_scaffold => true
map.resources :coaches, :active_scaffold => true
map.resources :equipments, :active_scaffold => true

The above code will generate a complete interface for our club.

Following code for your layout will provide a navigation bar in your view.

admin.html.erb

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <%= stylesheet_link_tag 'admin.css' %>
    <%= javascript_include_tag :defaults %>
    <%= active_scaffold_includes %>
    <title><%= "Admin" %></title>
  </head>
  <body>
    <div>
      <div>
        <h2>Agent Website Admin Panel</h2>
        <div>
          <ul class="links">
            <li>
              <%= link_to 'Sports', sports_path %>
            </li>
            <li>
              <%= link_to 'Players', players_path %>
            </li>
            <li>
              <%= link_to 'Coaches', coaches_path %>
            </li>
            <li>
              <%= link_to 'Equipments', equipments_path %>
            </li>
            <li>
              <%= link_to 'PlayersSports', playerssports_path %>
            </li>
          </ul>
          <div class="clear">
          </div>
        </div>
      </div>
      <div id="content">
        <div id="main">
          <%= yield %>
        </div>
      </div>
    </div>
  </body>
</html>

There are various customization options available. As per our requirement we can customize the columns, links, fields, actions etc. We would discuss them in the concluding part of the series.


Payal Gupta is working working as software engineer with Vinsol. She has over two years of industry
experience.


Did you like this? Share it:
01 Apr 2010

SSL checklist for Ruby on Rails Applications

RubyonRails, web development posted by sid

Cross posted from darthsid

The purpose of SSL is to provide a reasonable level of protection against eavesdropping and man-in-the-middle attacks. Although SSL provides a greater level of security, it introduces a lot of overheads and hence should be used sparingly. Two of the most common places to use SSL is for payment transactions and user registration/login.
This post intentionally focuses only on the Rails application as there are numerous post on the net for SSL setup on the server. Enabling SSL in a Rails application is really trivial and there are just a few points that need your attention..
Read more

Did you like this? Share it:
29 Mar 2010

Jquery Full Calendar with Ruby on Rails

RubyonRails, jquery, rails, ruby on rails posted by Akhil Bansal

Contrary to popular belief, working on a client project gives us a generous margin of creativity and explore innovative solutions. Take the example of a recent project I was working on. The client required a collaboration-based calendar module for their application similar to Google Calendar. Initially we started developing it from scratch , but then, we found an awesome Jquery plugin.

FullCalendar” provides a full-sized, drag & drop calendar. It uses AJAX to fetch events on-the-fly for each month. It also supports an intuitive interface to manage events that spans over multiple days or weeks. It is visually customizable and exposes hooks for user-triggered events (like clicking or dragging an event).

I decided to give it a try and utilize its hooks for user triggered events within our Rails application. This small effort resulted in a barebone Rails app that might provide a good base for your project which require calendar, scheduling or appointment features. I called it fullcalendar_rails and it is now available on github with a working demo at http://fullcalendar.vinsol.com.

Feel free to give your valuable feedback. I hope you will find this useful.

Update: On popular demand, I have added recurring events functionality with daily, weekly and monthly frequencies. It also allows for exceptions to recurring events including delete and edit features.



Did you like this? Share it:
16 Nov 2009

11 Things to Consider Before Deploying Your Ruby on Rails Application

deployment posted by kapil

At VinSol, we have been developing and deploying Rails applications for more than four years. During this period, we  have identified some best practices that we prefer to follow while deploying  rails application to production server.

Below is the checklist of these practices:

 

1. Ensure that NS records and MX records are changed if they need to be changed

Changing nameservers will point the domain to the hosting server,  and changing MX records will redirect incoming mails to the mail server. As a very first step, we should make sure that name servers of the domain are set to be the correct one.  Changing MX record is a must if our application is parsing incoming mails or we wants to use other mail services for e-mail exchange, for example Gmail.

 

2. Ensure some backup mechanism in place for both data as well as user uploaded content like images/documents etc.

Since production data is very critical, we must setup backup  mechanism. It could be some type of scheduled task that takes periodic backup of all critical data, Or it could be some type of backup service provided by hosting company. When we talk about critical production data, it includes production DB, content generated by application users like images, documents, etc.

 

3. Ensure database indexes

We might have done development without having proper database indexes, but we should avoid going to production without them. Adding indexes might slow down insert queries a bit but it increases the  performance of read queries. It applies when application in production has percentage of read operations much more than write operations.

 

4. Enable your slow query log

This is specific to MySQL. Enabling slow query log allows MySQL to log slow running queries to a file. And this log can be used to find queries that take a long time to execute and are therefore candidates for optimization.

 

5. Ensure exception capturing is in place

We might want to be notified when something bad happens to our application. There are several hosted services available who receive and track exceptions, for example Hoptoadapp.com, GetExceptional.com etc…  Either we can choose one from these hosted services or we can use “exception notifier” plugin.

 

6. Ensure adding entries for cron/scheduled jobs

Most of the applications have some functionality/jobs that need to be run periodically, for example generating invoices, sending newsletters etc.  In most cases these jobs are done by a rake task. We should make sure that we have added such jobs to cron or similar program.

 

7.  Monitoring important processes

To ensure that our site is up 24×7 we need to ensure that all processes that our application needs are up. There can be many processes like MySQL, Mongrel, Apache etc.. These processes are very important as our application directly depends on them. For example if MySQL process get killed accidentally, our application would not be able to connect to MySQL and will start throwing exceptions.

We can choose any of the available monitoring tools like God, Monit, 24×7 etc…

 

8. Ensure confidential data filtering

We would never like to leak/share confidential information of our application users. We should make sure that none of the user’s confidential data like SSN, Credit card info, password are being written to log files. We might not have paid much attention on this while developing the application.

 

9. Rotate log files

Once our site is up and running, every single request write some text in log file. And hence size of the  log file keeps on increasing. Larger log files can put us in trouble if we get it beyond certain size. Its difficult to manage these log files, as larger files need more memory to open and need more time to download. In one of the rescue project we did , the log file size was 3GB.

We would recommend having logrotate setup for the application.

 

10. Setup Asset Host

Setting up asset hosts can reduce loading time by 50% or more. We must setup asset hosts for our application. Once asset hosts are all set, our static files will be delivered via asset hosts for example asset1.hostname.com, asset2.hostname.com

 

11. Clearing up stale sessions

We should make sure we should not left any stale session on the server. If our application is using DB or file system  as session store, we must add a schedule task to delete stale sessions.

These are some of the points we have identified from our past experience and we might be missing some. Feel free to  always add them as comments, and I’ll keep this post updated.


Akhil is a senior software engineer working with Vinsol for last 5 years. He is an inhouse deployment ninja.

 

 

We also provide affordable rails deployment services.

 

 

Did you like this? Share it:
12 Nov 2009

10 little known ways to find a ruby on rails team for your next project

Developers, Tools posted by kapil

Everytime we talk to our clients, we find that they are not aware of lot of options through which they can find a good rails developer. Usually clients go to odesk and other freelance websites to find rails developers. Following are  10 more ways to find  rails company/developer for your next dream project :

  1. Post your requirements on twitter with hashtag #ruby #ror #rails
  2. Go to Railsdevelopment.com - its a directory of rails companies. You can search for specific services with your budget ranges.
  3. Working with Rails – Again a directory of rails developers and companies. You can browse through specific industry categories.
  4. Local Ruby Meetups – The most passionate guys are always there in local meetups. For eg: we have delhi ruby meetups and you can find all local meetups in australia here
  5. RubyJobs – Post a job on rubyjobs or rubyinside job board. There are some country specific ruby job boards.
  6. RubyonRails wiki – There is a wiki of ruby on rails companies.
  7. Open Source Contributions – Sites like http://agilewebdevelopment.com/ gives you a directory of rails plugins. Open Source contributions such as releasing a Rails plugin, or fixing bugs on projects , or Rails itself, demonstrates exposure to other Rails code bases and quality of a developer. Search for developer name in github.
  8. Conferences – Conferences are good way to find quality rails developer or team.
  9. Facebook – Few people post jobs on facebook.

Few tips :

  • Don’t hire someone that doesn’t know Rails at all. Yes, we have seen some people doing it.
  • Ask for references of previous clients if possible in your country.
  • Look for someone who values the money you are paying them and will make your investment in them provide a valuable return.
  • A personal Rails blog is a good indicator of  developer’s interests , experience and resume.
Did you like this? Share it:
Next Page »« Previous Page