Hello…hope someone can help. I have a has_many through relationship
set up but am not able to get it to work properly. As you can see I have
users, roles and a user_roles table. To verify things are working I
created an ‘intro’ page with associated action in an ‘admin’ controller.
The action simply finds the name of the user that’s logged in and should
display their role name.
@user = User.find(session[:user]).roles.name
The trouble is it just displays the word ‘Role’ on the intro page not
the users role name. If I change it to
@user = User.find(session[:user]).username
it will display the username properly, anyone know why this is
happening?
Thanks…Bill
-----------------------DETAIL-----------------------------------------
mysql> desc roles;
±------±-------------±-----±----±--------±---------------+
| Field | Type | Null | Key | Default | Extra |
±------±-------------±-----±----±--------±---------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
±------±-------------±-----±----±--------±---------------+
mysql> desc users;
±--------------±-------------±-----±----±--------±---------------+
| Field | Type | Null | Key | Default | Extra |
±--------------±-------------±-----±----±--------±---------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(255) | YES | | NULL | |
| password_salt | varchar(255) | YES | | NULL | |
| password_hash | varchar(255) | YES | | NULL | |
±--------------±-------------±-----±----±--------±---------------+
mysql> desc role_users;
±--------±--------±-----±----±--------±---------------+
| Field | Type | Null | Key | Default | Extra |
±--------±--------±-----±----±--------±---------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| role_id | int(11) | YES | | NULL | |
| user_id | int(11) | NO | | 0 | |
±--------±--------±-----±----±--------±---------------+
class Role < ActiveRecord::Base
has_many :role_users
has_many :users, :through=> :role_users
end
class User < ActiveRecord::Base
has_many :role_users
has_many :roles, :through=> :role_users
end
class RoleUser < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class AdminController < ApplicationController
def intro
@user = User.find(session[:user]).roles.name
end
end
intro.html
…
<%= @user %>
…