John Philp wrote the following on 29.05.2006 16:57 :
I want to be able to hide the Label part if the user is not an
Administrator and output it if the user is.
It should work as is (minus the missing % after “end” problem).
One remark, though :
you should not have a “session[:role]” if role is a user property.
You should probably code an accessor like the following, made available
through application.rb and application_helper.rb:
current_user ? current_user.role : nil
# Cache the User instance (probably used multiple times in a
return @cached_user if @cached_user
# The find (:first …) instead of a “find(id)” avoids
exceptions when the id isn’t in DB
session[:user_id] ? (@cached_user = User.find(:first,
=> [ ‘id = ?’, session[:user_id]])) : nil
@cached_user avoids multiple calls to the DB. You end up 1/ restoring
the session, 2/ doing a single find for your user on each request
instead of only 1/ restoring the session.
Roughly the same amount of data is transferred but this is a little bit
slower than a single request. So why bother? You get a lot of robustness
for a very small perf penalty, see below.
Your login method should only put the logged-in user id in session.
Otherwise you’ll get multiple problems:
when restoring sessions you’ll need various models pre-loaded when
restoring the user (depending on the objects stored in the session
through the user instance which can cache itself other objects), in
short all associated models must be loaded by a
model :, …, :
line in application.rb to avoid such problems.
when changing the user model, you can’t restore the sessions anymore
(objects dumped with old models can’t be restored with the new one),
changes applied to the logged in user or associated cached objects
aren’t visible if done by using other instances of the same objects (in
other sessions but also in the same session…).
In short, you’ll avoid a lot of trouble by neither storing more than the
smallest bit of information you need in session: the user id. In
practice, the perf penalty isn’t even noticeable.