Related Link

Permalinks

A permalink is an attribute of a Story, so we’ll need to modify our schema so that one can be stored for each story. We’ve already seen migrations in action each of our existing migrations was generated when we created a new model. Now we need to expand an existing model, so that we can add a permalink attribute to the Story model.

To add a migration without adding a new model, we use the generate script, passing migration as the first parameter:
$ ruby script/generate migration AddPermalinkToStories

This code generates a single migration file by the name of db/migrate/003_add_permalink_to_stories.rb. Edit this file so that its contents reflect the following:

class AddPermalinkToStories < ActiveRecord::Migration
def self.up
add_column :stories, :permalink, :string
end
def self.down
remove_column :stories, :permalink
end
end

Unlike our previous migrations, here we’re modifying the structure of an existing table, rather than creating a brand new one. The add_column function fills this role nicely:
add_column :story, :permalink, :string

The syntax of the add_column function is almost identical to that of the create_table function we’ve used before we just need to pass it the name of the table we want to modify, and the name and type of the column we want to add.
In this case, we’re adding a column with the name permalink, of type string, to the stories table.
In previous migrations, we haven’t needed to modify the self.down method, but this time we’ve added a line to it:
remove_column :stories, :permalink

When this migration is reversed, we want to remove a single column, rather than drop the entire table (which would be extremely bad news). As with add_column, remove_column takes symbols as its parameters. These symbols represent the
table that’s being modified, and the name of the column that we’re removing.
We don’t need to specify the column type when we’re removing a column, so this isn’t included as a parameter.
Go ahead and apply this migration using the rake tool:
$ rake db:migrate

This will add the new column to the stories table, the output of which is shown below:

To finish off this little exercise in altering our app’s infrastructure, we need to populate our newly added permalink column with a value for each of the stories that have already been added to our database.

From the Rails console, fetch a single Story. Update its permalink attribute using the update_attribute method:
>> s = Story.find(:first)
=> #
>> s.name
=> “My shiny weblog”
>> s.update_attribute :permalink, ‘my-shiny-weblog’
=> true
>> s.permalink
=> “my-shiny-weblog”

As you can see, the permalink I created for this entry is loosely adapted from the name of the Story: spaces have been replaced with dashes, and uppercase letters with lowercase letters.

Thanks for Reading.

Favorite Link