Oomoo

September 17, 2008

The “V” in MVC

Filed under: ajax, forms, IDE, MVC, rails, view — oomoo @ 8:42 pm

Probably one of the hardest adjustments to make when transitioning from Desktop forms development to browser-based is the endless number of code and template files that must be created and maintained just to have one working “form” (that you will now be calling a “page”). 

With a traditional desktop form, it usually isn’t hard to get your arms around all of the “players” involved in making your form work.  You may have many “layers/tiers”, but most of the pieces are probably written in the same language using the same IDE.  This is not the case when designing web pages/forms where the content for each page is spread across several files (at a minimum) each of which are probably using very different development languages and/or markup styles.  

Why have all of these “pieces” of code and/or markup all over the place?

  1. MVC (Model View Controller)
    The MVC architecture dictates separation between your data/business logic (model), your application code (controller), and the web page presented to the user (view). The “View” in “MVC” really means “a combination of all the pieces needed to create a finished page/form”. 
  2. DRY (Don’t Repeat Yourself)
    DRY is one tenet of Rails development.  It basically says “if you are copying/pasting the same code/markup into multiple files, that code/markup should be put into it’s own file which should just be pulled into the pages that need it at run-time.”  Yes, that is my own paraphrase 🙂
  3. WWW = Best Of Breed
    Web development has accelerated the pace at which tools and technologies are evolving.  We web developers love to complain about all the “disconnectedness” that exists in web-based apps, but we would really scream if some new technology came out and we had to wait a year for some company to boil out the impurities and then bloat it up so it could be “assimilated” before we could work with it (wait, I know that company…).  HTML, CSS, and JavaScript are poster-child technologies for “survival of the fittest” or should I say “survival of the most flexible but yet most simple”… nah, doesn’t have the same ring to it.

So, with just these three demands placed on us as a pre-requisite for developing a web form, it’s no wonder that we end up with so many disparate technologies and pieces all needing to converge without errors inside multiple versions of non-standard browser implementations across multiple operating systems.  Oh man, my stomach just knotted up right there… okay, Ruby and Rails to the rescue!

 

Anatomy Of A View

The following “pieces” are used to produce a single web page/form:

HTML (ERB)

The main part of a web page or “form”.  It resides in \app\views\modelname\myview.html.erb.  Many people consider this the “view”, but it is only one component of the view.  This one file actually contains many types of coding/markup/templating.

  • HTML – text, tags, tables, etc.
  • ERB – in-line Ruby including object/variable references, custom method calls, helper method calls, etc.
  • CSS – in-line style settings override external CSS stylesheet settings.
  • JavaScript – in-line JSP method calls  (can also contain JavaScript methods).
  • Images – icons, pictures, borders, backgrounds, etc. located in \public\images\
  • Flash – or Silverlight, or some other 3rd party client control.

CSS

Your cascading stylesheet(s) which control most of the presentation properties of your page/form.  You will almost always have at least one of these for each application.  It is very likely that you will have several.

  • CSS stylesheets are stored in \public\stylesheets\.
  • Which stylesheet to use is usually established in either an application-level or a controller-level Layout file like this:  
    <%= stylesheet_link_tag ‘mystyle’ %>

 

JavaScript

Your JavaScript classes/functions and 3rd party tools like Scriptaculous, Prototype, and JQuery.   Your application will usually use at least 3 JSP libraries.   Large AJAX-driven client applications can have…lots of them!

  • JavaScript code files are stored in \public\javascripts\.
  • Usually, the Layout file will include:
    <%= javascript_include_tag :defaults, :cache => true %>
    which will include the 5 most commonly used javascript libraries (including Scriptaculous and Prototype).
  • You can also specify
    <%= javascript_include_tag :all, :cache => true %>
    which will automatically include EVERY javascript file found in \public\javascripts\
  • You can also specify
    <%= javascript_include_tag ‘prototype’, ‘effects’, ‘controls’, :cache => true %>
    to control which libraries load or the order in which they are loaded.

 

Helper(s)

Helpers blur the line between a Controller and a View.  As Dave Thomas so brilliantly put it, “A helper is simply a module containing methods that assist a view.  Helper methods are output-centric.  They exist to generate HTML (or XML, or JavaScript)-a helper extends the behavior of a template.”

  • Helpers are stored in \app\controllers\helpers\ 
  • Controller-specific Helpers are named after their Controller with “_helper.rb” appended to the end.
  • The Application-wide Helper is \app\controllers\helpers\application_helper.rb

Layout(s)

A layout is kind of like an HTML/ERB fragment or snippet that gets pulled into your page template at run-time and is usually used to show data/text on the page this is generic across all views/pages for the Controller (like headers, footers, borders, etc.).   

  • All layouts are stored in \app\views\layouts\
    (defined by the constant TEMPLATE_ROOT)
  • Controller-specific layouts are named after their Controller.
  • The application-wide Layout named “application.html.erb”
  • The application-wide layout can be specified in \app\controllers\application.rb
  • Each Controller can override the application-level layout by setting the “layout” property or by passing
    :layout => ‘layouts/mylayout’
    directly in the render( ) method call.
  • You can suppress the use of any Layout by including
    :layout => false
    in the render( ) method call.

Partial

Partials are very much like Controller-level Layouts because they are HTML/ERB fragments that get pulled into your page and rendered at run-time.  The big difference is that Partials are typically used to display repetitive formatted information (like a grid with rows of records) using a code block (DO…END block).

Partials must be manually called for in your HTML/ERB file like this:
<%= render :partial => "clientlist", :locals => { :f => @f, :label_text => "Update"} %>

This will render the partial _clientlist and pass it the local variables (from the Controller) and the set the variable “label_text” to the value "Update"

Rails 2.0 introduced the ability for a Partial to have it’s own Layout.  Yes, it does seem a bit like nesting, but it is nice to have!  Now, we can do something like this in our HTML/ERB file:
<%= render :partial => "header", :Layout => ‘boxed’ :locals => { :post => @post} %>
which will pull in the Layout _boxed.html.erb, which will then pull in the Partial _header.html.erb.

  • Partials are usually used on a “per View basis” and are stored in \app\views\myview\
  • Partials are named beginning with an underscore (i.e.  _mypartial.html.erb)
  • Partial Layouts are stored in the same folder as the Partial and also begin with an underscore.
  • You can re-use a Partial Layout across your application if you store it in
    \app\views\application\

    Then, when calling the partial, just use 
    :layout => ‘layouts\mylayout’

RJS

RJS templates also blur the line between the Controller and the View.  They have access to all of the Controller objects/variables, but they also have an object reference to the current HTML “page” that is in the browser.  RJS templates allow you to infuse JavaScript into your views that is written using Rails “helper methods” (instead of actual JavaScript).  Separate RJS template files are not required (you can accomplish most of the same things with “render updates” directly in your Controller code). 

  • RSJ template files are stored in \app\views\myview
  • RJS templates are named for the Controller “Action” from which they are called with a “js.rjs” extension.
  • RJS templates are not actually “called”, if one exists, it is simply applied when the view is rendered.
  • Make sure you don’t try to name an RJS template the same thing as the View, otherwise the View gets rendered, not the RJS.

 

 

So…

I just showed you how you could easily have 7 or more separate files using 5 or more different technologies included in the 1 page you are trying to display to the user.  Hopefully, knowing is half the battle and at least the reasons “why” make a little more sense to you now.  I also gave you a fairly concise list of the places where the creation/display of a Ruby On Rails “View” can go wrong.  Using Ruby On Rails can sometimes seem like magic, and that is part of the fun.  But, you at least need to know that there “is” someone behind the curtain and try to get as familiar as you can with the plumbing because one day it will back up!

 

How To Debug

Debugging an application with hundreds of files and so many combined technologies is no small feat.  The first step is to remember that all of these “pieces” eventually get smashed back together into the HTML displayed in the browser!  So, you can view the source of the page in the browser (Using the IE Developer Toolbar in Internet Explorer, or even better, using the Firebug plugin for FireFox).

Use a full-blown IDE with a built-in debugger (like Aptana with RadRails, Steel Sapphire, Komodo, etc.)

Use the Logs!  Look at your log files, and don’t forget that you can pepper any problem code with manual log entries.

Use the IRB!  The interactive Ruby console will allow you to spy on your objects and variables as well as manipulate them in real-time.  Yes, it’s command-line Alice.

Use some of the great tools and techniques laid out in this post: Rails Guide – Debugging

 

*This post uses Rails 2.1 and Ruby 1.8.

Advertisements

September 2, 2008

Rails Is Not A Language

Filed under: classes, gems, rails, ruby — oomoo @ 2:02 pm

Say it with me… “Rails Is Not A Programming Language”.  Thanks!  It’s easy to forget sometimes that all the magic of Rails is actually riding on a foundation of Ruby.  Rails is a “Web Application Framework” that is written in Ruby.  Ruby actually IS a programming language, Rails is a set of  classes/packages designed to do a lot of the tedious work typically involved in writing a web-based application. 

Ruby is very extensible, owing much to the fact that it is basically compiled on-the-fly.  This means that Ruby can pull in chunks of code as needed and integrate them as new functionality or to augment/override even base functionality.  Usually, these additional pieces of functionality are in the form of “Gems” (get it… Ruby… Gems).  Well, Rails itself is actually just another Ruby Gem (technically a collection of Gems)!  You install Rails (and update it going forward) using the same Ruby commands you would use to install any other Ruby add-on.  I suppose that Rails seems like a language because it actually becomes your interface to Ruby, wrapping Ruby “the language” inside of itself.

The idea behind Rails is to abstract complexity whenever possible, integrate existing 3rd part tools whenever practical, and provide structure, intuitiveness, and design simplicity wherever probable.  Installation of Rails automatically includes the base packages (ActiveRecord, ActionController, ActionView, etc.), a back-end ruby web server called WEBrick, and the JavaScript libraries “Prototype” and “Script.aculo.us” to do the pretty AJAX stuff in the browser.  So, with all of these typically independent pieces neatly wrapped up into one integrated package, it is easy to see why so many people initially mistake Rails for a programming language.

 

The Rails framework does a great job of things like:

  • Giving you the feel of working in an integrated environment.  It does much of this by replacing traditional HTML-only files with a pseudo-HTML file into which you can combine Rails objects and variables and Rails method calls directly (in-line) with your HTML, CSS, and JavaScript.
  • Integration of JavaScript (Prototype and Script.aculo.us) into Rails helper methods hiding some of it’s complexity
  • Taking care of routing web requests
  • Creating secure communication sessions
  • Generating e-mail
  • Ability to generically output to many formats (XML, HTML, etc.) with almost no additional coding
  • Automatic integration of a testing environment for unit and application regression tests

 

Where it really shines is helping you create database applications, since it will help you do things like:

  • Handle database transactions
  • Performing data validation
  • Automatically show/update related records
  • Record locking/detection of stale data
  • Generating automated testing routines
  • Performing SQL without writing pages full of SQL
  • Maintain the state/values of variables and objects between your web pages and your code
  • Performing database record caching inside easy-to-use memory objects. 

 

Rails “encourages” (almost demands) standardized folder structures, file naming, and method naming conventions.  This may feel limiting to some at first, but the payoff is extraordinary.  It infers a level of self-documentation to every project.  It makes it much easier for new developers to join a development team at any stage. It also makes technical documentation and blogs such as this one easier to write because so many things can simply be assumed about the development environment.

The naming standards, request routing, and other basic concepts in Rails afford you some additional cool abilities when it comes time to move/change your application/server/database:

  • instantly move your applications between development, test, and production
  • duplicate/rename an entire application without making any code changes
  • change your back-end database “from” just about any database technology “to” just about any database technology with no code changes
  • change your server-side

 

In Summary…

  • Rails is not a language
  • Ruby is a language
  • “Ruby on Rails” is the official name 
  • “Rails on Ruby” would probably be a more accurate description, but it just doesn’t roll off the tongue as well or sound quite as sexy.

Can you write a Ruby on Rails application without learning Ruby?  It is a testament to the depth of the Rails framework that you actually could write any number of fairly simple web applications without learning a tiddle of Ruby.   You obviously are still “using” Ruby, even if you don’t really understand it.  Doing this, however, would not be a very wise undertaking.  It would be like planting your very first garden without knowing the first thing about dirt, water, sunlight, or (dare I say it) bugs.

 

Wanna try Rails?

Have a Mac?  Rails is built in, see my post:  Is Mac Perfect for Rails Development

Getting Started?  See my post:  Getting Started Tips

Try Ruby without the Rails (in your browser):  Try Ruby

If you want to see some other web frameworks, look here: Wikipedia – List of Web Application Frameworks

August 20, 2008

How Do I ‘Refresh’ Individual Form Fields?

Filed under: ajax, controller, forms, model, rails, view — oomoo @ 11:13 pm

Recently, I wrote about creating a Ruby on Rails app that would create HTML formatted signatures for Outlook and web-based e-mail systems  (see: Outlook and the Double-Spaced Signature ).  This small application was my first chance to do true data-based entry using form fields (most of my prior RoR projects just tapped into existing databases for searching and presentation in a browser).

Well, most of my software development background has focused primarily on creating data-based applications with heavy data-entry and reporting, so I was eager to see if Rails was up to the task.  I used the Scaffolding classes built into Rails 2.1x to initially generate the pages (see, I wanted to call them screens or forms) to do the CRUD work, then I set about understanding how they worked and editing them to look a little better.

I understand the whole “disconnected” “stateless” model of web development, but I never dreamed it would be this dang hard to put a drop-down box and a couple of text fields inside form tags on a page and get them to interact with my database and with each other.  Of course, now that I know how to do it, it seems simple (and Rails is great again, the web makes sense, and all is right with the world).  Of course, what I could have finished in VFP in about 60 seconds took me many frustrating hours with more than one Rails/Ajax book thrown across the room.

For this application, I only have 2 tables (told you it was simple); Locations and Signatures.  The “Locations” table is a lookup table containing information that will be related to multiple “Signatures” (usually one Signature per person).

Locations Table:Locations schema

Signatures Table:Signatures schema

 

 

 

 

 

 

 

 

 

Locations.id  — Relates to —>> Signatures.location_id

Since each Signature relates back to a Location, if the Company changes their logo or web site, no change to the Signature record is needed, you need only regenerate the HTML signature for Outlook.  Okay, enough “database theory 101”.

Here is what I wanted to accomplish:

captured_Image.png Display a page where the user could select their “Location” from a drop-down combo field…

 

 

 

…once selected, the data from the “Location” phone/fax fields would automatically populate the first two phone fields of the “Signature” record. SigAfterLocation

…the phone fields would temporarily “highlight” to indicate to the user that something had changed

…then the fields would go back to their normal color, still containing the updated data from the Location record.

captured_Image.png[4]

 

 

 

 

Finally, the user “Saves” their Signature, and clicks the “Create My Signature” link which generates/downloads the HTML file containing their nicely formatted Outlook Signature.

captured_Image.png[6]

 

Piece-O-Cake!!!  No really, I wrote a complete version of this page using my desktop development tool (VFP) and it took me almost no time to have all the logic working and I even had a browser preview of the finished HTML that updated itself as you updated your signature.   Here is a screenshot of my desktop form written in VFP…

captured_Image.png[29]

 

We need our page to contain:

  • A Form (form_for)
  • A Drop-Down List (collection_select)
  • Some Labels (form.label)
  • Some Fields (form.field)
  • A Submit Button (form.submit)
  • Some way to know when a selection has been made from the drop-down list
  • Some way of updating the page based on the drop-down selection

 

    <% form_for @signature do |f| %>
    <div id="cbo_location_id", style="height: 31px">
        <%= f.label :choose_location, "Choose Your Location:", 
                    :style => "top: 5px; left: 3px; position: relative; color: white; font-weight: bolder;" %>

        <%= collection_select("signature", "location_id", @locations, "id", "loc_name", 
                              options ={:prompt => "...Select A Location", 
                              :include_blank => false}, 
                              html_options={:style => "top: 7px; left: 15px; position: relative;"}) %>
                              
        <%= observe_field("signature_location_id", 
                          :url => { :action => "location_lookup" }, 
                          :with => "'id=' + value") %>
    </div>
    
    ...other form fields here...

        <table width="350" height="150" cellpadding="0" cellspacing="0">
           <tbody> <tr> <th align="center"> <%= f.label :phone_desc, "Desc.", :style => "color: white;" %> </th>
                        <th align="center"> <%= f.label :phone_num, "Number", :style => "color: white;" %> </th></tr>
                   <tr> <td align="center"> <%= f.text_field :sig_p1_desc, :size => "10", :style => "" %>  </td>
                        <td align="center"> <%= f.text_field :sig_p1_num, :size => "20", :style => "" %>   </td></tr>
                   <tr> <td align="center"> <%= f.text_field :sig_p2_desc, :size => "10", :style => "" %>  </td>
                        <td align="center"> <%= f.text_field :sig_p2_num, :size => "20", :style => "" %>   </td></tr>
                   <tr> <td align="center"> <%= f.text_field :sig_p3_desc, :size => "10", :style => "" %>  </td>
                        <td align="center"> <%= f.text_field :sig_p3_num, :size => "20", :style => "" %>   </td></tr>
                   <tr> <td align="center"> <%= f.text_field :sig_p4_desc, :size => "10", :style => "" %>  </td>
                        <td align="center"> <%= f.text_field :sig_p4_num, :size => "20", :style => "" %>   </td></tr>
             </tbody>
          </table>

    <div style="height: 35px"> <p> <%= f.submit "&nbsp;Save&nbsp;" %>  </p>  </div>
  <% end %>

 

We need our form to:

  • Know that a selection has been made from the drop-down list:

       ( \app\views\signatures\edit.html.erb )

    <%= observe_field("signature_location_id",                           
                       :url => { :action => "location_lookup" },
                       :with => "'id=' + value") %>
  • Retrieve the chosen “Location” data:

      ( \app\controllers\signatures_controller.rb )

    class SignaturesController < ApplicationController
    
      def location_lookup
        @location = Location.find(params[:id])
      end
      ...other controller methods...
    end
  • Update/refresh the fields on the page that have changed, and highlight them: 
      ( \app\views\signatures\location_lookup.js.rjs )

    page[:signature_sig_p1_desc].value = 'p.' page[:signature_sig_p1_num].value = @location.loc_phone.strip page[:signature_sig_p2_desc].value = 'f.' page[:signature_sig_p2_num].value = @location.loc_fax.strip page.visual_effect :highlight, :signature_sig_p1_desc, :duration => 2 page.visual_effect :highlight, :signature_sig_p1_num, :duration => 2 page.visual_effect :highlight, :signature_sig_p2_desc, :duration => 2 page.visual_effect :highlight, :signature_sig_p2_num, :duration => 2

 

So, what is happening here?

  1. My drop-down list is:

        <%= collection_select…  %>
  2. When it’s value is changed, my “field observer” gets fired:

       <%= observe_field…  %>
  3. It’s "action" is defined as:

        :url => { :action => "location_lookup" }  
    which means it is going to call the controller action/method named "location_lookup"
  4. As a parameter, it is going to pass the "id" of the Location chosen:

       :with => "’id=’ + value"
  5. The "location_lookup" action/method in the controller "finds" the passed in Location ID:

       @location = Location.find(params[:id])
  6. Then (by magic) rails renders the contents of the RJS file.

    Actually, Rails will always look for an RJS file to exist that is named the same as the controller action/method.
  7. The RJS file will first update the field values with the contents of the Location data:

        page[:signature_sig_p1_num].value = @location.loc_phone
  8. Then, the RJS file will temporarily "highlight" the changed fields:

       page.visual_effect :highlight, :signature_sig_p1_num, :duration => 2

 

*Note – we didn’t need to use an RJS file, we could have achieved the same thing by putting the RJS code directly in the "location_lookup" controller action/method:

def location_lookup
  @location = Location.find(params[:id])

  render :update do |page|
    page[:signature_sig_p1_desc].value = 'p.'
    page[:signature_sig_p1_num].value = @location.loc_phone.strip
    page[:signature_sig_p2_desc].value = 'f.'
    page[:signature_sig_p2_num].value = @location.loc_fax.strip

    page.visual_effect :highlight, :signature_sig_p1_desc, :duration => 2
    page.visual_effect :highlight, :signature_sig_p1_num, :duration => 2
    page.visual_effect :highlight, :signature_sig_p2_desc, :duration => 2
    page.visual_effect :highlight, :signature_sig_p2_num, :duration => 2    
  end 
end

I just prefer to use the RJS file to keep my controller clean of view-specific things, and if you just think that the RJS is taking the place of the View (html.erb) that would normally be rendered after a controller action/method, then it makes sense.

*Note: "page" is an automatic reference to the existing web page object (DOM) that Rails is exposing so we can monkey around with it.  Now, isn’t that nice!

Since RJS is basically just "Railsified" javascript (AJAX), you can do just about anything to the existing web page.  You can add things, hide things, change all the colors, change the words, enable/disable things, and even insert calls to new javascript functions (like links to services on other web sites).

 

In review, the process involved really isn’t that different from what I had to code in my desktop VFP application.  The biggest difference was knowing what form elements to use (and their syntax) then just understanding that the full logic is done in pieces that are spread out over several files (view, controller, RJS).  In the end, the secret sauce for updating my field display is AJAX, simplified by the Rails helpers.

Happy Field Refreshing!!  –Oomoo

 

—UPDATE ––

Do you want to DEMO this application in your browser right now?

Just go here:  Outlook Signature Application

This web-based application is a full-featured signature generator for Outlook.  You can use it to create your signature or just use it as an educational tool.  This application was completely written at (and is hosted on) Heroku!!

(hint:  If you enter your “Location” and “Signature” information, be sure to delete it before leaving the site)

In fact, you can download the full source code here:  Download Source Code

August 19, 2008

Outlook and the Double-Spaced Signature

Filed under: Microsoft, rails, Windows — oomoo @ 9:43 pm

BTW, if you are not a programmer trying to create signature files, and you are just using Outlook and want to avoid double-spaced lines, simply hold down the [Shift] key when pressing the [Enter] key at the end of each line in your signature.  The signature editor (Word) will insert a "soft return" instead of a "hard return" and your signature will be nicely single-spaced.  If you are a programmer, read on…

So, the other day I’m called upon to write a web-based (Ruby on Rails of course) app for a client.  This app takes an employee’s information and generates a standard "company approved" signature block that can be used in both Outlook and web-based mail like GMail (Google Mail)/Yahoo/etc.  No big deal, everyone just uses HTML these days right?  Even Microsoft finally relented and HTML formatted messages are even the default in Outlook 2007.  Woo-hoo!  Word as an e-mail editor is finally dead!  I can’t tell you how many hours I have spent changing the default e-mail editor in previous versions of Outlook on client’s machines.

Back to the web app… 

Step 1, I did my research and found out that Outlook stores it’s signatures in the folder: C:\Documents and Settings\<user name>\Application Data\Microsoft\Signatures\   If I have an HTML signature named "MyWorkSig", it is actually stored in the signatures folder as MyWordSig.htm (not .html).  If it were a text signature, it would be stored in the same folder and have the same name, but would have a .TXT file extension (MyWorkSig.txt).  If it were an RTF (rich text format) signature, it would be stored in the same folder and have the same name, but would have a .RTF file extension (MyWorkSig.rtf). 

Step 2, I learned that you should not use CSS styles, but should "in-line" CSS formatting, which is just "style" information embedded into my HTML tags. 

style="font-size: 9px; color: #000000; font-family: Tahoma,Arial"

I also learn that you shouldn’t use the "html", "head", or "body" tags, because you are not really creating a full HTML page, just a piece of a page.

<html> <body> ....  </body> </html>

 

Step 3, after MUCH trial-and-error, I learned that the advice given on most websites about creating Outlook-compatible HTML signatures will just make your signature look crappy or will get your mail deleted by anti-spam packages because of embedded pictures or deceptive URLs.

Most sites will tell you to wrap your signature in one of these HTML tags/elements:

<div>...</div>    <p>...</p>     <table>...</table>

Why?  Well, if you don’t wrap your text in some type of HTML tag/element, you won’t be able to specify the "Style" information I eluded to in "Step 2".  This means that you won’t be able to format your signature with fonts or colors and you won’t be able to control the spacing/layout.  In that case, you basically have a TEXT signature, not HTML.

So, what’s the problem with using these tags in my signature?  Well, if you like lots of double-spaced lines in your signature, then go ahead and use them.  If you are like me and you want the signature coming out of Outlook to look the same as the one coming out of any web-based messages you send, then the infamous double-spaced Outlook signature is a fiasco!

When you send a message through Outlook, and your HTML signature encounters any "divider" tags, it will insert a double-spaced line.  It makes sense in a Microsoft-sort-of-way when you consider that each of the tags I mentioned are literally followed by a "hard return".  But, in a the-way-things-really-work-sort-of-way it’s just fubar’d.

So, how do you add divider elements/tags to your HTML so you can add your "style" settings without getting double-spaced? 

<span>...</span>

That’s right my fry-end, the lowly "span" tag will allow you to divide your text, specify all the formatting you spammy heart desires, but avoids the double-spaced line from hell.  Try this signature on for size:

   1: <table style="font-family:Tahoma,Arial; font-size:9px;" cellspacing="0" cellpadding="0">
   2:   <tr>
   3:     <td style="vertical-align: top; text-align: left;">
   4:       <span style="font-size: 12px; font-weight: bold;">Mr. Knows Itall</span>
   5:       <span style="font-size: 11px;"><br />Level 30 Cleric</span>
   6:       <span style="font-size: 12px; font-weight: bold"><br />Global Masters LLC</span>
   7:       <span style="font-size: 11px;"><br />phone: (777)-888-9999 </span>
   8:     </td>
   9:   </tr>
  10: </table>

You could just save this in your Outlook signature path (name it something like…. MySignature.htm), then pull up your Outlook signature settings, and choose (the newly available) MySignature as your signature.  Send yourself a message and you will see that no double-spaced lines appear (except following the "Table" tag, but we will let that one slide).

*Note that I had to manually insert "br" tags where I wanted a "line break" to appear.

 

Now, here is a full-blown HTML signature that has multiple tables for indentation, but the double-spaced lines Outlook will insert are almost useful to the end result:

<table style="font-family: Tahoma,Arial; font-size: 9px; color: #000000;" 
              cellspacing="0" cellpadding="0">
    <tr>
        <td>
        <table style="font-family: Tahoma,Arial; font-size: 8px; color: #000000; 
                      vertical-align: top; text-align: left; white-space: nowrap;" 
                      cellspacing="0" cellpadding="0">
            <tr>
                <th colspan="2" style="text-align: left">
                <img src="companyx_logo.jpg" alt="(CompanyX logo)" 
                          width="254" height="46" style="border-style: none" /></th>
            </tr>
            <tr>
                <td style="font-size: 8px; width: 60px; white-space: nowrap;">
                </td>
                <td style="vertical-align: top; text-align: left;">
                <span style="font-size: 12px; font-weight: bold;">Johnny B. Good</span>
                <span style="font-size: 11px;"><br />I.T. Warlock</span>
                <span style="font-size: 6px;"> <br /> <br /></span>
                <span style="font-size: 12px; font-weight: bold">CompanyX, Inc.</span>
                <span style="font-size: 11px;"><br />1 Main Street</span> 
                <span style="font-size: 11px;"><br />Hangemhigh, TX 666777</span> 
                <span style="font-size: 11px;"><br />p. 123-456-7890 f. 098-765-4321 </span>
                <span style="font-size: 6px;"> <br /> <br /></span>
                <span style="font-size: 11px;">
                  <a href="http://www.companyx.com" title="www.Companyx.com">www.CompanyX.com</a>
                </span>
                <span style="font-size: 6px;"><br /><br /><br /></span>
                </td>
            </tr>
        </table>
        </td>
    </tr>
    <tr>
        <td colspan="2" style="font-family: Tahoma,Arial; font-size: 9px; color: #000000;">
        PLEASE NOTE: This message, may include privileged blah blah blah...
        </td>
    </tr>
</table>

*Note: You will need to specify your own logo JPG, and change the width/height accordingly.  I chose to put my logo on the company website, and pull it from there instead of embedding it into the message.  Your mileage may vary using either technique.

*You will certainly want to make use of the "alt=" option in your "img" link (if you use one).  If, for any reason, your logo graphic is not downloaded/visible in the message, the "alt=" text will be what your recipient sees instead.

Learning all of this….interesting stuff….the hard way took me the better part of an 8-hour day (I am sad to say).  Hopefully, I just gave you back a few hours with your family.  Now, go home and tell them Oomoo sent you!

 

—UPDATE ––

Do you want to learn more about creating your own Outlook Signature Application? 

See this post: Application Notes

 

Do you want to DEMO this application in your browser?

Just go here:  Outlook Signature Application

This web-based application is a full-featured signature generator for Outlook.  You can use it to create your signature or just use it as an educational tool.  This application was completely written at (and is hosted on) Heroku!!

(hint:  If you enter your “Location” and “Signature” information, be sure to delete it before leaving the site)

In fact, you can download the full source code here:  Download Source Code

Update Rails/Rake/Gems

Filed under: gems, rails, rake — oomoo @ 9:09 am

Keep your Rails/Rake/Gems up-to-date by running these commands:

Update the RubyGems system itself (required by Rails 2.0).
gem update –system

Update Rails-specific gems and installs any new components (specifically Active Resource).
gem install rails

Update Rake, the build tool used by Rails.
gem update rake

Update the Ruby bindings for the SQLite3 database.
gem update sqlite3-ruby
. 

For an existing project, also do this:

rake rails:update

…and edit the config/environment.rb file and set the correct GEM Version:

RAILS_GEM_VERSION = ‘2.1.0’ unless defined? RAILS_GEM_VERSION

You might want to make sure your migrations are up-to-date:

rake db:migrate
rake db:schema:dump

 

Check your GEM version:
gem –version

 

Downgrade/Rollback GEM
gem -v

 

List all the installed gems by typing:

gem list

. 

View the documentation for all the installed gems by typing:

gem server

To access the documentation, point your browser to http://localhost:8808/

This command starts a web server on port 8808 by default. 

You’ll see a list of the gems you have installed with a link to their RDoc documentation.

 

Install SQLite3:
gem install sqlite3-ruby

 

Force Rails to use MySQL (instead of the default SQLite3):

rails -d mysql myapp

 

March 31, 2008

Is Mac “Perfect” for Rails Development?

Filed under: IDE, Linux, mac, rails, Windows — oomoo @ 5:32 pm
I’ve never been a Mac fanboy. I never actually “owned” a Mac either. In fact, it has always pissed me off the way that many of the Rails development blogs just assumed you were using a Mac or possibly Linux, but never (he whispers) “Windows”. The snide little way they would say “Okay class, open your terminal window and type: /script generate blah blah blah”, just assuming that I had a friggin terminal window and that I didn’t have to type “ruby” first.
Microsoft and I have been joined at the brain for quite a number of years now. It’s not the perfect relationship, I’ll admit. Bill doesn’t really listen to what I have to say like he did when things were all new and exciting. He is not interested in my “feelings”. He never asks, “So, how was your development day today?” Although, for a while, he did ask “where do you want to go today?” There have been times when he has gotten me excited about working on a personal project, just to pull the rug out from under me. Sometimes, we would find something to do together, then he’d just lose interest and walk away. I’d yell, “Oh sure, just walk away. Just like you always do when you aren’t the profit center of attention. Bill… look at me, Bill.. why won’t you even look at me!” But he would just keep on walking, leaving me sitting there with a lap full of J++, RDO, Visual InterDev, or our precious love-child Visual FoxPro.
It wasn’t long ago that Steve really started to entice me. He really shined up his Apple with that IPod, then started wearing down my defenses with the MacBook, the iPhone, then we got to a little bit of iTouch, and finally to OS/X. But, I couldn’t make the move, I had too much to lose and the price of change was just too steep. Then one day, we snuck out and were in the computer store, and he kind of nonchalently steers me over to the Mac section; “just to take a look”, he says. Well, it was all clean and nice, so I walk on over and he starts grinning like a schoolboy. There sat the cutest little machine, “it’s a Mac Mini”, he says to me as he is dropping to one knee, “and it’s cheaper than most PCs… besides Bill will never have to know”. I admit that I was swept up in the emotion of it all, and we ended up walking out there hand-in-hand around an extended 3-year warranty.
Now, Bill and I have been really trying to work things out. He showed me that Steel Sapphire has developed one of the slickest IDE’s available for doing Rails in Visual Studio. Just this afternoon, Bill asked me, “Just what does Steve have on his Mac that I don’t have in my Windows”. He stood there pushing his glasses up waiting for an answer. I sighed, then said “It’s just plain ‘easy’ Bill. You always make everything so complicated, and the Mac is fully loaded for Rails development right off the shelf. I don’t have to slave away installing and configuring over a hot CPU all day long, just to find out that everyone can’t agree on what they want. “
No, I’m not leaving Bill, not yet, I’ve got too much invested. But, now that I have Steve, I just can’t give him up. We have too much in common and we really enjoy being around each other. He just “gets” me. And it may be my imagination, but I think he really listens.  Somebody que the screensaver…
So, if you are new to Rails, or are thinking about learning Rails, you don’t “have” to get a Mac. But, if you want a seamless, easy, and enjoyable experience, if you want peace and harmony between your computer, your O/S, and your development, you owe it to yourself to give one a try. In fact, you could probably go down to your local computer store and create a working Rails application right on the demo machine. Try that on any of the non-Mac models! Ruby, Rails, and lots of Gems are already installed and configured. It just works (the first time)!

March 24, 2008

Getting Started Tips

Filed under: hosting, IDE, rails, ruby — oomoo @ 11:30 am

IDE – Integrated Development Environment

There are many Integrated Development Environments (IDE’s) available for the RoR developer. The choices vary a little across operating systems, but most tools are thankfully cross-platform. I hear the majority of the developers working on the RoR “core” use Mac. I also see lots of posts (especially Ruby ones) by the Linux crowd. Very few posts are Windows-specific. Being technology-agnostic, I actually own Windows, Mac, and Linux computers and devices of all shapes and colors. since I am still heavily involved in desktop apps, The majority of my development work is still done on Windows.

On the Mac, many developers are satisfied to use the text editing programs that ship with the O/S. Having used true Integrated Development Environments for so long, I just cannot live without the ability to design-code-test-repeat in the same environment, call me spoiled. I started my development career programming for DOS, writing “C” programs that had to manually manipulate the video buffer just to show a “form”. I have also done a good bit of Unix/Linux administration, so I am comfortable working from a command-line. But, I must say that the need to have various interfaces and command-prompts for running Apache, MySQL, RAKE, and Ruby made me feel like I was taking two steps back in my efforts to move one step forward on the web.

I am so very grateful and forever in debt to the fine cadre of programmers and development shops that are creating really top-notch IDE tools for Ruby and Rails developers. I am just now starting to see a light at the end of the IDE tunnel.

Ruby In Steel (Visual Studio plugin) (Visual Form Designer)
Steel Sapphire’s “Ruby In Steel” plug-in for Visual Studio has put itself on the cutting edge with their “Visual Form Designer”. That’s right folks, the ability to visually design RoR “forms” right in the IDE. In technical terms, it “smooshes” your view, helper, javascript, and css into what the user will see as the final form. You can then drag-n-drop controls on the “form” visually design it, and still get into the code or html and make edits to those. When you are done, it saves all the changes back to their original parts.

I like the safety of this approach, because it gives you one layer of seperation between the “composite” (smooshed together) form and your actual code. This abstraction allows you to do cool things like export the composite out to your favorite HTML editor, then pull it back in. It is also good, because as it is in beta, the tool has lots of bugs left in it. This is a very ambitious project, so I’ll be patient…. is it done yet?

Even aside from the Visual Form Designer, this is a good tool for straight coding and debugging as well. My big gripe, of course, is that it runs inside Visual Studio, which is a pig and a hog and slow and complex and… well, you get the point. It’s hard to be all things to all people and do any one thing really really well. If you are a Microsoft hugger though, you will think all the “crap” is just the way it is for everyone. Well, not so my friend, which is why you should check out some of these other great tools.

Aptana Studio (with RadRails plugin)
I use Aptana Studio every day. It is fast, clean, and quite comprehensive. Oh yeah, it’s FREE. It’s based on Eclipse and handles all things AJAX with aplumb. It also handles development for Adobe AIR, PHP, and iPhone (and it has a completely javascript server-side) if you need any of those things.

Aptana automatically treats your Rails application and associated sub-directories as a “project”, so there’s no need to create/maintain a project file. The real-time debugging support is excellent as is the ability to find/install new “gems” directly from within Aptana.

Heroku
Heroku is one of the most mind-bending development platforms I have come across. Heroku allows you to code, debug, and run your Rails application using nothing more than your FireFox browser. You can create code, upload/modify your database, and debug from any computer with an Internet connection. It is also “group aware” allowing your programming team to all collaborate within the same development space. Yes, there is source code control and the ability to backup your entire project to your PC anytime you like.

Heroku runs in the Amazon EC2 (elastic computing cloud) that means that server configuration does not exist. Just flip a switch and your Rails app is magically in “production”, nothing extra to configure, update, or support. The “elastic” in EC2 means that it should be quite scalable, allowing you to allocate resources as-needed. All this goodness is currently in Beta, so I don’t have any pricing or comparison statistics on the hosting side. But, even without the hosting, the ability to develop and test your complete Rails application from any PC is very exciting and perhaps the most unique play in the industry!

3rd Rail
3rd Rail is a Ruby/Rails-specific IDE from CodeGear (formerly part of Borland). It is a very nice IDE, but it is very “young” and seemed to lack some of the extra goodies incorporated by some of the more mature contenders. I have used Borland products many times during my development career and have always found them to be very solid and productivity driven. I will need to check back with 3rd Rail in a while to see how they are progressing.

Komodo
I purchased Komodo when I was playing with Python and Django (as part of my journey to find Rails). Komodo is very well respected in the Python community. Although I have not used it, I saw that Komodo also has a RoR plugin. If you are using Python or want to use both Python and Ruby, you should check out Komodo.

.

Development Stack (Ruby, Rails, Apache, MySql, SqlLite, etc.)

If you are lazy (I prefer to think of it as “not expending unnecessary cycles”) or you just want a quick way of trying out this whole crazy Ruby On Rails thing, you will want to use a consolidated “development stack”. This simply means that there is a master installer/configuration tool that, with one download, will install and configure all the pieces that go into making a RoR web development platform work. Once the “master install” is done, you have a tightly integrated installation of Apache, Ruby, Rails, and MySQL (or SqlLite or some other open source database) which includes a nice little interface to start/stop all these pieces as needed.

InstantRails

InstantRails is the tried-and-true one of the bunch. It did go through a short period recently where it was no longer supported. This gave rise to BitNami picking up the mantle. But, then InstantRails was once again revived and updated for Rails 2.0. It remains my choice.

BitNami

I tried BitNami a while back, but had troubles with the integrated install. Once InstantRails supported Rails 2.0, I must admit that I stopped trying BitNami. I may use it on a Virtual PC, just to see if they got all the wrinkles ironed out.

.

Books (be sure to get books covering Rails 2.0)

There are tons of books covering RoR. Here are a few I found very helpful. Each of them comes from a different viewpoint, so you will benefit by reading multiple books by different authors. You never know which one of them will explain a certain thing in just the right way to make your little lightbulb come on!

Why’s Poignant Guide To Ruby (http://poignantguide.net/ruby/) (fee and very entertaining)
Programming Ruby – The Pragmatic Programmer’s Guide (Dave Thomas) (known as “PickAxe”)
Agile Web Development with Rails (Dave Thomas)
Ajax On Rails (Scott Raymond)
Build Your Own Ruby On Rails Application (Patrick Lenz)
Ruby For Rails (David A. Black)
Beginning Ruby – From Novice to Professional (Peter Cooper)
The Rails Way
The Ruby Way
The Ruby Programming Language

.

Web Sites (there are also tons of blogs and such)

For in-depth examples and free code, nothing beats the really greats RoR blogs out there!

But, here is a tiny sampler of some of the more “authoritative” Ruby/Rails websites:

Official Rails Site: http://www.rubyonrails.com/
Official Ruby Site: http://www.ruby-lang.org/en/
Offiicial Blog: http://weblog.rubyonrails.org/
API Reference: http://api.rubyonrails.org/
Rails Wiki: http://wiki.rubyonrails.org/rails

ScreenCasts/PodCasts/Workshops
PeepCode: http://peepcode.com/
Rails PodCasts: http://podcast.rubyonrails.org/
Rails Workshops: http://rubyonrailsworkshops.com/
Ruby Learning: http://rubylearning.com/

*As my daddy used to tell me (on an almost daily basis) “well son, you’re not gonna learn any younger”.

March 11, 2008

Variables Across The MVC

Filed under: MVC — oomoo @ 1:53 pm

Here are some notes about variables, scoping, etc.

Variables in Ruby/Rails are of your fairly standard variety (local, instance, public).  There is another type called “class” or “class instance” variables that get way too much attention for the amount they are used (or not used) in most apps.  If you are learning Ruby/Rails, just ignore Class Variables for now and don’t use them. 

As with most languages/frameworks, it’s the “visibility” of variables that is important.  This is especially true with web-based applications.  Ruby is based on MVC (Model/View/Controller) architecture (see http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/ for a good MVC overview)

In the diagram shown at the website referenced above, notice that the Browse interacts with the Controller, which gets data from the Model, then passes it back using the View.

Models, View, and Controllers are just classes.  Rails hides their complexity making them seem like magic, but they are just Ruby classes.

Models        are ActiveRecord classes 
Views         are ActionView classes 
Controllers  are ActionController classes

Controllers and Views have a special arrangement though, since both of them are part of ActionPack.  This means they actually share a codebase.  (see http://ap.rubyonrails.com/ for a thorough a picture and an explanation)

…snippet…  “Action Pack splits the response to a web request into a controller part (performing the logic) and a view part (rendering a template). This two-step approach is known as an action, which will normally create, read, update, or delete (CRUD for short) some sort of model part (often backed by a database) before choosing either to render a template or redirecting to another action.   Action Pack implements these actions as public methods on Action Controllers and uses Action Views to implement the template rendering.  Some of the features, are tied to ActiveRecord, but that doesn’t mean that Action Pack depends on Active Record. Action Pack is an independent package that can be used with any sort of backend.” 

What this means for you, is that instance variables defined in a Controller are visible to any View called by that controller. 

Local Variable

      current_time = Time.now 

      If defined in a Controller, it can NOT be seen from “any” View called by the Controller. 
 

Instance Variable

      @current_time = Time.now 

      Can be seen only from “this” instance of this class

      If defined in a Controller, it can be seen from “any” View called by the Controller. 
 

Class (instance) Variable

      @@current_time = Time.now 

      Can be seen and changed from “any” instance of this class (one variable shared across all instances)

      If defined in a Controller, it can be seen from “any” View called by the Controller. 
 

Public/Global Variable

      $current_time = Time.now 

      Can be seen and changed from “anywhere” 
 
 
 

An Example 
 

\app\controllers\application.rb

$current_time = Time.now     # Global Variable  (visible everywhere) 
 
 

Controller

class OrdersController < ApplicationController

  def index

    @orders = Tblorder.find_recent_orders   # Call Model Method “find_recent_orders” 

    @filter_scope_name = “Recent Orders”   # Set Instance Variable (visible by view) 

    render :action => ‘list’     # Show the View

  end

end 
 

Model

class Order < ActiveRecord::Base 

  @filter_recent_days  = 15     # Instance Variable (NOT visible by view because this is the Model) 

  def self.find_recent_orders

                                                      # “sql” is a local variable  (not visible anywhere else)

    sql = “SELECT * FROM orders where DATEDIFF(curdate(), ordDateOrderTaken) <= “ + @filter_recent_days.to_s

  

    find_by_sql(sql)

  end

end 
 

View

<!– Most of the HTML is in \app\views\layouts\orders.rhtml –> 

<% if @orders.length == 0 then%>

  <p> No Orders Exist.</p>

<% else %>

  <% if @filter_scope_name %>     # Using Instance Variable from Controller

    <caption><%= h @filter_scope_name %></caption>

    Current Time: <%= $current_time %>     # Using Global Variable from file application.rb

  <% else %>

    <caption>Order List</caption>

  <% end %>

<% end %> 

<% for order in @orders %>

  <%= link_to order.id, :action => ‘show’ %> <br />

  <%= order.ordCustPONum %> <br />

  <%= order.ordOEM %> <br />

  <%= order.ordDescription %> <br />

  <%= order.ordModelNum %> <br />

  <%= order.ordSerialNum %> <br />

  <%= order.ordFinalDisposition %> <br />

  <%= order.ordDateOrderTaken %> <br />

<% end %> 
 
 

A Note About Controller Methods

Even though your Controller Instance Variables will be visible to your View, your Controller Methods will not.  You can get around this by placing methods that need visibility to the View in your Controller Helper (app\helpers\orders_helper.rb based on our example above). 

“Model” Relationships

Filed under: model, rails — oomoo @ 1:47 pm

Notes about how Relationships work in Rails Models.  I created the examples and pulled some of the notes from the API doc.
 

http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html 
 
 

“belongs_to” – Means “this class is a child of the class that is named in the belongs_to statement”. 

“parent class”  –  Use the mixed case singular form. 

“foreign key field”  –  Use the signular form of the parent class name with _id appended. 
 
 

Example: 

class Order < ActiveRecord::Base

  set_table_name “orders”

  set_primary_key “ordPK” 

  #tblOrders belong to customers, use the orders.ordcustpk field.

  belongs_to :customer, :foreign_key => “ordCustPK” 

  #Orders belong to CustomerContact,

  #but only when the field CustomerContact.custconPrimary = 1

  belongs_to :customercontact,  :conditions => “custconPrimary=1” 

  #Customer

  belongs_to :shipment, :foreign_key => “ordShipPK”

end 
 

class Customer < ActiveRecord::Base

  set_table_name “customers”

  set_primary_key “CustPK” 

  has_many :orders, :foreign_key => “ordCustPK”

  has_many :customercontacts, :foreign_key => “custconCustPK”

end 
 

class Customercontact < ActiveRecord::Base

  set_table_name “customercontacts”

  set_primary_key “custconPK” 

  #orders belong to customers, use the orders.ordcustpk field.

  belongs_to :customer, :foreign_key => “custconCustPK” 

  #CustomerContacts has many Orders,

  #  related through Customer, using the key index Orders.ordCustPK.

  #To link Orders to Customer.  (the link from

  #  CustomerContacts to Customers is already specified above)

  has_many :orders, :through => :customer, :foreign_key => “ordCustPK”

end 
 

class Shipment < ActiveRecord::Base

  set_table_name “shipments”

  set_primary_key “shipPK” 

  #Each Shipment only has one Order (one-to-one relationship)

  has_one :order

end 
 
 

One-to-one

Use has_one in the base, and belongs_to in the associated model.

  class Employee < ActiveRecord::Base

    has_one :office

  end

  class Office < ActiveRecord::Base

    belongs_to :employee    # foreign key – employee_id

  end 

One-to-many

Use has_many in the base, and belongs_to in the associated model.

  class Manager < ActiveRecord::Base

    has_many :employees

  end

  class Employee < ActiveRecord::Base

    belongs_to :manager     # foreign key – manager_id

  end 

Many-to-many

There are two ways to build a many-to-many relationship.

The first way uses a has_many association with the :through option and a join model, so there are two stages of associations.

  class Assignment < ActiveRecord::Base

    belongs_to :programmer  # foreign key – programmer_id

    belongs_to :project     # foreign key – project_id

  end 

  class Programmer < ActiveRecord::Base

    has_many :assignments

    has_many :projects, :through => :assignments

  end 

  class Project < ActiveRecord::Base

    has_many :assignments

    has_many :programmers, :through => :assignments

  end 

For the second way, use has_and_belongs_to_many in both models. This requires a join table that has no corresponding model or primary key.

  class Programmer < ActiveRecord::Base

    has_and_belongs_to_many :projects       # foreign keys in the join table

  end 

  class Project < ActiveRecord::Base

    has_and_belongs_to_many :programmers    # foreign keys in the join table

  end 

Choosing which way to build a many-to-many relationship is not always simple. If you need to work with the relationship model as its own entity, use has_many :through. Use has_and_belongs_to_many when working with legacy schemas or when you never work directly with the relationship itself.  

Is it a belongs_to or has_one association?

Both express a 1-1 relationship. The difference is mostly where to place the foreign key, which goes on the table for the class declaring the belongs_to relationship. Example:

  class User < ActiveRecord::Base

    # I reference an account.

    belongs_to :account

  end 

  class Account < ActiveRecord::Base

    # One user references me.

    has_one :user

  end 

The tables for these classes could look something like:

  CREATE TABLE users (

    id int(11) NOT NULL auto_increment,

    account_id int(11) default NULL,

    name varchar default NULL,

    PRIMARY KEY  (id)

  ) 

  CREATE TABLE accounts (

    id int(11) NOT NULL auto_increment,

    name varchar default NULL,

    PRIMARY KEY  (id)

  ) 
 
 
 

Partial List of Options:

:class_name – specify the class name of the association. Use it only if that name can’t be inferred from the association name. So has_one :author will by default be linked to the Author class, but if the real class name is Person, you’ll have to specify it with this option.

:conditions – specify the conditions that the associated object must meet in order to be included as a WHERE SQL fragment, such as authorized = 1.

:order – specify the order in which the associated objects are returned as an ORDER BY SQL fragment, such as last_name, first_name DESC

:foreign_key – specify the foreign key used for the association. By default this is guessed to be the name of the associated class in lower-case and _id suffixed. So a Person class that makes a belongs_to association to a Boss class will use boss_id as the default foreign_key.  
 
 

Examples:

belongs_to :firm, :foreign_key => “client_of”

belongs_to :author, :class_name => “Person”, :foreign_key => “author_id”

belongs_to :valid_coupon, :class_name => “Coupon”, :foreign_key => “coupon_id”, :conditions => ‘discounts > #{payments_count}’

Some Rails Naming Conventions

Filed under: rails — oomoo @ 1:43 pm

Just notes about some of the naming conventions used by Rails.  I pulled this info from various sources and filled in the rest.
 

Model/Class Table/Schema 

    Table (in database) – Plural, with underscores instead of spaces between words  (ie: steering_wheels)
    Model / Class – Singular, first letter Capitalized, CamelCase for models (ie: SteeringWheel) 
    Model/Class      Table/Schema
    Order                orders
    LineItem            line_items
    Person               people
    Address             addresses
    Legacy               legacies
    Mouse               mice 
     
    *Foreign key fields are named…  tablename_id     (i.e.  customers_id, orders_id) 
    *id  (Every table automatically gets a key field of “id”  (just plain old “id”)) 
    *created_at, created_on, updated_at, updated_on  (IF USED, rails will automatically update these fields) 
    *lock_version  (IF USED, automatic field used for “optimistic locking”)  (integer, default=0, null=false) 
    *counter_cache  (field used to save database lookups) 
    *type  (IF USED, allows “single table inheritence”) 
    *mytable_count  (IF USED, allows rails to calculate the # of objects created for the class) (when you define it, make it default to zero) 
    *position    (IF USED, “position” is used when sorting objects in a “acts_as_list” class) 
    *parent_id    (IF USED, foreign key column in an “acts_as_tree” model) 
    *lft and rgt    (IF USED, provides nested set enhanced tree-like functionality “acts_as_nested_set”) 
    quote_value
    template 
     
     

Controllers 

    Class Name           File Name   
    WeblogsController        weblogs_controller.rb
    LineItemsController  line_items_controller.rb 
     
     

Views 

    Folder Name       File Name                                  
    web_logs            index.rhtml  (this is just the default, any number of html files can exist here)
    line_items           index.rhtml   
     
    /app/views/orders/index.rhtml 
    Helper:
          /app/helpers/orders_helper.rb 
          Module Name = OrdersHelper 
    To access the view from a browser, if you are using index.rhtml, you just need to specify the view folder name:
    *If you create a file at app/views/layouts/application.rhtml it will automatically be used as a wrapper around all other layouts. 
     
Older Posts »

Blog at WordPress.com.