0

我有以下型号:

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

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

怎么打印出来?

4

3 回答 3

2

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

user.roles.map(&:name)
于 2013-05-14T09:19:02.513 回答
0

尝试这个。

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

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

于 2013-05-14T09:17:35.660 回答
0
user.assignments.each do |a|
  puts a.name
end
于 2013-05-14T09:18:10.913 回答