2013-05-14 30 views
0

我有以下型号:Rails - 如何找出用户在系统中的角色?

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 

我试图找出用户的角色,但是当我尝试

user.assignments.name 

它不会从表中打印出用户的角色角色 (列名)。

如何打印出来?

+0

我有很多角色,如何找出我的系统中的作用是什么? – oldergod 2013-05-14 09:13:36

回答

2

您需要在您的关联映射,以获得特定的字段:

user.roles.map(&:name) 
+0

感谢您的评论,当我尝试这个时,我得到了'' – user984621 2013-05-14 09:21:43

+0

查看我更新的帖子,应该是user.roles.map(&:name) – 2013-05-14 09:22:41

+0

非常感谢你真是太棒了! – user984621 2013-05-14 09:25:01

0

试试这个。

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

你不能调用user.assignmentsname的方法,因为它是一个数组。

0
user.assignments.each do |a| 
    puts a.name 
end 
相关问题