Friday, November 9, 2007

Tutorial: Adding a Markup field to a Rails App

Recently we added a Textile-based text markup field to an internal webpage. We used the RedCloth library. It was very easy:

1. Install RedCloth
This is dead simple using gem:
# gem install RedCloth
Bulk updating Gem source index for:
Successfully installed RedCloth-3.0.4

2. Add a Database Column to Hold the Text
We'll make a Rails migration so that this change can be tracked:
$ cat db/migrate/053_add_constraints_to_styles.rb
class AddConstraintsToStyles < ActiveRecord::Migration
def self.up
add_column :styles, :constraints, :string

def self.down
remove_column :styles, :constraints

3. Add Test Data
This part is so that we can see if our view will work before adding the editing capability (which I'll show next time):
# ./script/console
Loading development environment.
>> p = Style.find("04600")
>> p.constraints
=> nil
>> p.constraints = "Test: _this_ string +is+ *textile*"
=> "Test: _this_ string +is+ *textile*"
=> true
>> exit

4. Modify the View
In the view I first add just
<%= @style.constraints %>
to make sure the model is pulling the right data. Looks good, so now go for the gold!
<%= %>