After creating the team object, there are a couple of things I want to do. First, I want to make sure a name is entered when a team is created. I fire up Intype (my favorite rails text editor), open the project, and open team.rb under the models folder. I edit it to look like this
class Team < ActiveRecord::Base
validates_presence_of :name
end
Now if I try to make a team but don't type in a name, I get this:
Next, in Intype, I open teams_controller.rb and note that @team = Team.find(params[:id]) appears a number of times, namely in the Show, Edit, Update, and Destroy defs. To DRY that up (don't repeat yourself), I'll put that in a before filter. The top of my teams_controller.rb now looks like this:
class TeamsController [:show, :edit, :update, :destroy]
def index
@teams = Team.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @teams }
end
end
That says before Show, Edit, Update, or Destroy are run, run a method called find_team. That new method goes at the bottom of teams_controller.rb
def destroy
@team = Team.find(params[:id])
@team.destroy
respond_to do |format|
format.html { redirect_to(teams_url) }
format.xml { head :ok }
end
end
private
def find_team
@team = Team.find(params[:id])
end
end
Now if I ever need to change that code, I can change it in one place rather than four.
