Forum: Ruby on Rails [roles/users]I give up, please help

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
357e326199208e143c8e967fe3b27b06?d=identicon&s=25 Tim Vo (timz)
on 2006-01-16 07:15
> Im testing ruby on rails and to practice i set my mind on making a login
> system. because i would come across of regularly made source.

> files:

user_controller.rb, user.rb

> my table layout:

users: |id|username|password
usertypes: |id|name| (admin, moderator, guest)
users_usertypes: |usertype_id|user_id| (+foreign key assocc)

> i have this in my user.rb file:

class User < ActiveRecord::Base
  has_and_belongs_to_many :usertypes, :join_table =>"users_usertypes"
end

class Usertype < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table =>"users_usertypes"
end

> in the user_controller (or application controller) are methods like this
> (sadly i cant gettem to work)

> # this method should verify if the active user has an 'admin' usertype
> # connected to it

def auth_by_type(type)
  @user = User.find(@session[:user_id]) #this searches for current user
  if @user.usertype == type
    flash[:notice] = "You are authorized as an #{type}"
  else
    flash[:notice] = "You are not authorized to view this page..."
    redirect_to :action=>:login
  end
end

def create
  #insert a new usertype in the users_usertypes table
end

def update
  #update a usertype in the users_usertypes table
end

> how can i use a method with an attribute such as auth_by_type in a
> before_filter. I tried:

before_filter :authorize_by_type("admin")

> but that doesnt work...
> Ive been spending hours and hours on this simple thing but i cant fix it.
> arghh

> I have a couple of questions.
> 1. How can i update/set the usertype of a user
> 2. How can i see if a user has a usertype 'admin' name
> 3. How can i use the method from 2. in a before_filter
C8a634a01a2c4508360874bff7fb1a7f?d=identicon&s=25 Kevin Olbrich (olbrich)
on 2006-01-16 13:32
tim vo wrote:
# connected to it
>
> def auth_by_type(type)
>   @user = User.find(@session[:user_id]) #this searches for current user
>   if @user.usertype == type
>     flash[:notice] = "You are authorized as an #{type}"
>   else
>     flash[:notice] = "You are not authorized to view this page..."
>     redirect_to :action=>:login
>   end
> end
>
>

My first guess is that you are having trouble with the 'type' keyword.
type is both a ruby keyword and a magic column name used for single
table inheritance.  Using it outside of those contexts will cause you
endless headaches unless you are really careful.

Change that name to something like 'kind' and try it again.

_Kevin
This topic is locked and can not be replied to.