Re: Login controller additions

Marcel Molina Jr.
Sat, 12 Mar 2005 16:18:12 -0000

On Thu, Mar 10, 2005 at 04:35:40PM +0100, Jonas Montonen
wrote:
> I have added roles and roles_users table and updated the model so that
> my users can have multiple roles.
> ("Admin" role does always have id = 1).
>
> I have added these methods to my application controller.
>
>  helper_method :is_admin?
>  helper_method :is_user?
>
>  def is_admin?
>      if @session[''user'']
>        @session[''user''].roles.find(1)
>      else
>        false
>      end
>  end
>
>  def is_user?
>    !@session[''user''].nil?
>  end
>
>
> The problem is that if a user does not have the role "admin"
(id=1) the
> @session[''user''].roles.find(1) statment fails with error
"unable to find
> role with id = 1".
>
> How can I do this another way..... I know it must be simple... but
I''m
> really a Rails/Ruby newbie ;)

In addition to the recommendations that jarkko and seckar offered here are
two other ways to get around find raising an exception. one way is to (ab)use
the dynamic finders.

    def is_admin?
      @session[''user''] ?
@session[''user''].roles.find_by_id(1) : false
    end

Another way is to use rescue.

    def is_admin?
      @session[''user''].roles.find(1) rescue false
    end

Though don''t use rescue cavalierly. You could cover up what might be an
unrelated exception.

marcel
--
Marcel Molina Jr. <marcel-WRrfy3IlpWYdnm+yROfE0A@public.gmane.org>