Category Archives: Ruby on Rails

Refactoring Tip: Eliminating Model.find(params[:id]) Duplication

In a controller, you’ll commonly have a method that requires you have an instance variable containing the object you’re working with. An example would be the show, edit, update, and destroy methods (REST).

To eliminate having find(params[:id]) in multiple methods, you can use before_filter, like this:

class Admin::PostsController < Admin::ApplicationController
  before_filter :find_post, :only => [:show, :edit, :update, :destroy]
  rescue_from(ActiveRecord::RecordNotFound) { |e| render :text => "

Post not found

" } def index @posts = Post.find(:all) end def show end def new @post = Post.new end def create @post = Post.new end def edit end def update end def destroy end protected def find_post(id = params[:id]) @post = Post.find(id) end end

(Thanks Jon)

Using Javascript to Populate Forms During Development

During development, working with forms quickly gets annoying because you have to constantly fill in each field, sometimes with unique info. One way around this is to write a little Javascript code that just populates the fields. I use something like this on the bottom of the form. I had jQuery no-conflict mode on in this case. In your app you might be able to get away replacing _j() with $():

<% if ENV['RAILS_ENV']=='development' -%>


<% end -%>

Mephisto for the Masses – Installation HOWTO

I’ve recently taken a fancy to Mephisto, a blogging-platform written in Rails. I have nothing against WordPress, but being in Ruby and using Liquid for themes, Mephisto is far easier (and more fun) to tweak and configure, especially when I want to migrate my sites away from the “blog look” and make them more dynamic.

It’s unfortunate development isn’t as active as say, Typo (also a Rails app, but I haven’t tried it), but I find that Mephisto at its current level makes a simple and fast starting point for most of my projects.

The point of this post is to address numerous problems with the installation. These are present in the tarball release of 0.8 Drax, and in trunk (as of 10/21).

Git The Code

Get the files, either the compressed archive or from edge (recommended).

git clone git://github.com/technoweenie/mephisto.git

Pre-installation

You’ll need to freeze rails 2.0.2, and have the latest tzinfo gem installed:

gem install tzinfo 
cd mephisto/ 
rake rails:freeze:edge RELEASE=2.0.2

The file it downloads should be named rails_2.0.2.zip and NOT rails_edge.zip.

Copy the “new” boot.rb into the config/ folder, overwriting the existing one:

cp vendor/rails/railties/environments/boot.rb config/boot.rb

Now rename the database sample file in config/ to database.yml and edit it to fit your own DB settings. You’ll probably only be using production.

Bootstrapping

Now bootstrap:

rake db:bootstrap RAILS_ENV=production

If it works, GREAT. But you’ll probably get an error or two. If you’re getting the following error:

Error message:
  undefined method `initialize_schema_information' for module  
  `ActiveRecord::ConnectionAdapters::SchemaStatements'
Exception class:
  NameError

You forgot to copy over boot.rb from vendor/rails/ – scroll up. If you’re getting an error that redcloth is missing (no such file to load—RedCloth-3.0.4/lib/redcloth), even though it’s in vendor/, it’s because the path to RedCloth is relative in config/environment.rb. Change it from:

require '../vendor/RedCloth-3.0.4/lib/redcloth' unless Object.const_defined?(:RedCloth)

to

require File.join(File.dirname(__FILE__), '../vendor/RedCloth-3.0.4/lib/redcloth') unless Object.const_defined?(:RedCloth)

Running

After the bootstrap, you may either start the server (ruby script/server, thin, mongrel, etc), or go with mod_rails (Phusion Passanger). I recommend the latter – Passenger is amazing, and the error screen is pretty.

Just point your Apache2 vhost to Mephisto’s PUBLIC/ dir. Here’s an example:


   ServerAdmin mrEman@domain.com
   ServerName domain.com
   ServerAlias www.domain.com

   # DocumentRoot must be rails_app/public/
   DocumentRoot /home/kiwi/www/domain.com/public/public
   Railsenv production

   DirectoryIndex index.html index.htm index.php
   ErrorLog /home/blue/www/domain.com/log/error.log
   CustomLog /home/blue/www/domain.com/log/access.log combined

Restart Apache2, and you’re done. The site should work right away. If you get the following error:

No such file or directory - /tmp/mysql.sock

It’s because the socket file resides somewhere else on your (host’s) distro. Just find (man find, locate, etc) and add a symlink to it. Here’s an example (Debian):

ln -s /var/run/mysqld/mysqld.sock mysql.sock

If you’re getting an error that gems you know you have aren’t found, like:

no such file to load -- tzinfo (MissingSourceFile)

it is due to the fact that Gems are not located anywhere Ruby checks. You’ll have to explicity pass Ruby -rubygems or require ‘rubygems’ — what a nuisance. Open config/environment.rb and add the latter line:

# requires vendor-loaded redcloth
require 'rubygems'

This will be global. Now either restart the server you ran (i.e., thin), or tell mod_rails to restart the app. To do so, just create a file named “restart.txt” in the tmp/ folder of the RAILS app:

cd mephisto_root/
touch tmp/restart.txt

and refresh the page. Passenger will restart the app and restart.txt will vanish.

The default login for the /admin page is admin/test. Wasn’t that a blast?

How To Use Fixtures to Populate Your Database in Rails

UPDATE: I’ve been using this method for awhile now: http://railspikes.com/2008/2/1/loading-seed-data

Seed data is data that the app is dependent on. It is data that has to exist if you were to wipe the database clean and reload your schema. Some examples would be a list of cities/states, a list of categories, or the initial ‘admin’ user account.

Most people looking at this thread want seed data rather than to populate their database with test/generated content. For the latter, you can go the route below or try Forgery

This is a response to the email I’ve been getting asking me how to use fixtures to load data into a database.

You want to create dummy entries in your Rails app, either for testing, for development, or for production, to make your site appear popular. Whatever the reason, populating your database can be done easily using fixtures.

While rake/fixtures/migrations can get a lot more complex, this will be a brief introductory example.

Initial App setup

$ rails characters
$ cd characters/

Edit config/database.yml – We only need a development database. So open up PHPMyAdmin or the MySQL command shell and:

mysql> CREATE database characters_development;
Query OK, 1 row affected (0.00 sec)

(I’m assuming you’re using MySQL. You can use anything; SQLite, Postgres, etc..)

Create a model and a table in the database (using a migration)

$ script/generate model Character
      exists  app/models/
      exists  test/unit/
      exists  test/fixtures/
      create  app/models/character.rb
      ....

$ vim db/migrate/001_create_characters.rb

Sexy migration:

class CreateCharacters < ActiveRecord::Migration
  def self.up
    create_table :characters do |t|
      t.string  :name, :alias, :motto
      t.timestamps
    end
  end

  def self.down
    drop_table :characters
  end
end

Now migrate development (default environment):

$ rake db:migrate

Create the characters fixture

$ vim test/fixtures/characters.yml

Continue reading How To Use Fixtures to Populate Your Database in Rails

Got API? Instantly Search API Documentation

gotAPI.com does an excellent job congregating API documentation for numerous programming languages under an AJAX interface. No more bulging neck veins or fulmination when you can’t remember the order of those pesky arguments.

No support for your favorite language? Contribute.

You can add a gotAPI Search Widget to your site: http://www.gotapi.com/widgets/index.html
See Ruby/Rails widget below (requires Javascript). Still in beta and might have UI issues, but it’s functional. Try typing map or validates and hitting enter.

Quick Ruby / Rails lookup

powered by gotAPI.com

Simple Way to Populate a Database in Rails

This is how I populate my database when I have a lot of data but can’t be bothered to write more than a quick throw-away hack. This doesn’t use fixtures, nor migrations (nothing wrong with them, I wuv migrations). Just a ruby file and the Rails console (this is optional actually).

I create a new rb file in lib/ (you can put your files in a sub-directory or anywhere ‘load’ can find them), then write the data I want inserted into the database in a new function in that file. I do so exactly as I would insert data in Rails. Model.create, Model.new, etc…

I then get into the Rails console (ruby script/console) and do load ‘file.rb’ and simply call the function. The database used will vary according to the environment you’re in (test, development, etc). Using ‘load’ every time you call your function(s) is preferred. Load will keep reloading the file (as opposed to ‘require’ which only reads a file once), staying up to date with edits you’re making to the file. For example, in the console:

>> load ‘funk.rb'; add_default_settings

(funk.rb is in /lib/ and add_default_settings is a function in that file)

As of 2.x, Rails now has rake db:migrate:reset and db:migrate:redo, which sends you down one migration and then back up to the current migration (or you can decide how many hops to take back using STEP=n). This is great, especially for tasks like populating a database.

So why don’t I use migrations? I do, but sometimes, especially in a proof-of-concept or throw-away app, I find it faster to skip the proper methods and write up a quick function. If you think that’s bad, you should see my lingering Python addiction. Sometimes I catch myself metaprogramming Ruby code in Python.

Introduction to Validations & Validation Error Handling in Rails

Purple Nitraguard Security Keypad

Validations in Ruby on Rails are essentially nothing more than methods that ensure that the data in a model is valid before saving it to the database. Traditionally, we validate data coming in using conditional expressions (for example, if email != NULL or if passwd==passwd_confirmation). This task is essential, but boring and tedious, but Rails’ validations make this mundane part of programming as simple and as easy as possible. The validations provided in Rails (defined in every model) are thorough, likely covering all your needs right out of the box. There are even validations provided for checking whether a user agreed to a Terms of Service or End-User License Agreement (EULA), and for doing automatic field confirmation, useful when you ask the user for an email or password twice to ensure no misspelling.
Continue reading Introduction to Validations & Validation Error Handling in Rails

Expanding List of Ruby on Rails Sites, Editors, Tutorials, Cheat Sheets and More

Most of these Ruby on Rails related links are right out of my bookmarks. I checked for 404s and added more recent entries, but this list is far from complete. New blogs, sites, tutorials and tools are released on a daily basis. Just leave a comment or contact me if you want your link(s) or anything related added, or have spotted any broken links.

(Updated 02/22/2008. Keep the suggestions coming!)

Continue reading Expanding List of Ruby on Rails Sites, Editors, Tutorials, Cheat Sheets and More

Understanding Basic Database Relationships in Rails

Nixon ERD

This short tutorial will be beneficial for you if database relationships and keywords like belongs_to and has_many confuse you, or if you’re trying to find out how relationships are implemented in Rails. As we create a small demonstration project, you’ll see that one beauty of Rails is how it does most of the work gluing everything together, after you’ve supplied it with information about your database’s structure.

But first — why bother learning about relationships? Very simply, they eliminate a major problem called an update anomaly, and they will probably save you disk space. Having info repeated in multiple entries can be problematic. How would you update a mass misspelling? Would you even notice a misspelled entry? Database normalization and multiple intertwined tables (via relationships) can curb this problem. Fortunately, ActiveRecord makes this easy.

For example, if you store the name and location of all your users in the same database table, you might be wasting disk space by having the same information repeated in multiple entries. You would be wasting a lot of space if your clam-cake-vendor-review site has hundreds of users living in “the State of Rhode Island and Providence Plantations.” This can be eliminated by having the locations tied to unique IDs in their own table, and associated to a user by their ID. This also makes renaming a location easy. Changing “the State of Rhode Island and Providence Plantations” to “Ocean State” is only done in one location, once.

Rather than going over all possible types of relationships here, I will be covering the very basics; Enough to help you grasp the main idea and see how it is implemented in Rails. Let’s begin by designing a simple project.
Continue reading Understanding Basic Database Relationships in Rails

Using Vim as a Complete Ruby on Rails IDE

vi traced with an optical mouse

NOTE: If you are experiencing segmentation faults with vim and rails.vim, see this post.

When coding in Ruby on Rails, you’ll usually be switching between files and running scripts a lot. It can be time-consuming and frustrating coding Rails using a traditional text editor designed for working on big files individually. Vim lets you hop around within a file with enough speed to activate the cosmic treadmill – but without a plethora of hacks and custom key mappings, it’s weak as a Rails IDE. Fortunately, for those of us who are reluctant to kick the vim habit, Tim Pope comes to the rescue with rails.vim; A plugin that makes working with Rails in vim painless and efficient. In this guide, I will explain how to install and use rails.vim, along with a few other plugins you’ll find useful when writing Rails applications.
Continue reading Using Vim as a Complete Ruby on Rails IDE