Session variable data validation

I’ve been using rails for about a month and I’ve been noticing that most
of my controller functions use values from my session variable. I find
that I write something like:

person = Person.find(session[:person])
if( person )

else
flash[:notice] = “unable to retrieve person”
redirect_to( :action => index )
end

It seems redundant to write similar code for every action. I could use
a hook to check the value before each action, but then I would be
accessing my database twice for the same data. Is it overkill to be
making sure something wasn’t deleted out of the database on each action?
How bad is it if my page tries to use an objec that is nil? What is the
standard practice?

Thanks for your help,
Chris

Brian,

Thanks for the help! I didn’t realize that I could access any instance
variables I create within a filter. This makes things much easier :-).

Chris

Here’s how I’ve done it before…

class PersonController < ApplicationController
before_filter :get_person, :only =>[:show, :edit, :update, :delete]

def list
@people = Person.find :all
end

def show
end

def edit
end

def update
if @person.update_attributes params[:person]

end

def delete

end

private
def get_person
begin
@person = Person.find session[:id]
rescue
flash[:notice] = “No person could be found with that ID.”
redirect_to :action => “list”
end
end

end

get_person makes @person available. You use it as a before_filter on
the
methods where you need it.

Just a thought. Remember, if you do @ person.find params[:id] and that
person isn’t there, it will throw an exception… your if block won’t
work.That’s why the above block catches the exception.

This particular example has not been tested for typos but it should work
for
you.

-bph

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs