Tag Archives: 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 -%>

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

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

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