A Ruby on Rails Journey

June 14, 2010

Fixing Up Teams

Filed under: TenthHole — Dick @ 1:30 am

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.

Advertisement

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.