im using rails 3.2.3 and am gettign weird values in my app.
I have 2 models, a user and role, which are a has_and_belongs_to_many relation. The middle table is created with role_id and user_id column and correct name (roles_users).
The thing is, when I assign a user to a role (upon creation through a checkbox) and then view all the users with roles associated to them I get invalid role id(like 75216410 when it sould be just 1 or 2) and the role name is just “Role” instead of admin.
I want to use Devise and CanCan, I’ve set up Devise but this thing keeps me from going.
My roles and users controller has the traditional restfull actions, the exact same ones we get when we scaffold. And since the DB values are correct, I believe this isn’t the issue.
My models are:
user.rb
class User < ActiveRecord::Base
# Devise modules
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable, :registerable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
#relationships
has_and_belongs_to_many :roles
#nested attr
accepts_nested_attributes_for :roles
# Accessible (or protected) attr
attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :role_ids
# attr_accessible :title, :body
#validations
validates :username, :presence => true
validates :username, :email, :uniqueness => true
end
role.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
attr_accessible :name, :user_attributes, :role_id
end
My users and roles views are the same you would get by a scaffolding as well.
My users index:
<% @users.each do |user| %>
<tr>
<td><%= user.username %></td>
<td><%= user.email %></td>
<td><%= user.roles.id %></td> #should display "1"
<td><%= user.roles.name %></td> #should display "admin"
<td><%= link_to 'Show', user %></td>
<td><%= link_to 'Edit', edit_user_path(user) %></td>
<td><%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
The thing is, this displays, instead of the role id (1), some random number like 69067380. If I refresh, this number changes to another random number. As for the Role name, it always says “Role” instead of “admin”.
This reminds me of a pointer memory address, but i doubt it is the case.
NOTE: When I check the tables with MySQL workbench, everything is fine and all the values in the tables are correct.
Any help is appreciated, thanks in advance
You user has many roles so when u fires
user.rolesit will give an array instead of single record tryuser.roles.firstoruser.roles.first.try(:name)it display first role.you can iterate role and display them as per your requirement.