Rails - how to find out user's role in the system?

I have following models:

class Role < ActiveRecord::Base
  has_many :assignments
  has_many :users, :through => :assignments
end

class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

class User < ActiveRecord::Base
  has_many :assignments
  has_many :roles, :through => :assignments
  ...
end

I am trying to find out user's role, but when I try to

user.assignments.name

It doesn't print out the user's role from the table roles (column name).

How to print out that?

Answers


You need to map on your association in order to get a specific field:

user.roles.map(&:name)

Try this.

user.roles.each {|role| puts role }

You can't call name method on user.assignments because it's an array.


user.assignments.each do |a|
  puts a.name
end

Need Your Help

Form Resizing Responsive issue textarea

html css forms textarea responsive-design

I've got an issue with my responsive textarea. It works fine (across different sizes) until the user tries to expand the form (I've currently got it locked in size with a

AMQP 1.0 support in ActiveMQ - can't set prefetch

activemq amqp prefetch qpid

We're trying to build a job queue system on top of ActiveMQ 5.9.1. We're using the AMQP 1.0 support in activemq, currently using the qpid jms library for the client code.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.