Ruby on rails 钢轨活套和浇注问题
我在Ruby on rails 钢轨活套和浇注问题,ruby-on-rails,casting,Ruby On Rails,Casting,我在用户模型中有以下方法 def get_employees @employees = [] groups.each do |i| @employees << Group.find(i).employees end @employees end def get_员工 @雇员=[] 组。每个组都有| i| @员工>>用户.查找(4).获取员工 >=>[[电子邮件地址:”test@gmail.com", >创建于:
用户
模型中有以下方法
def get_employees
@employees = []
groups.each do |i|
@employees << Group.find(i).employees
end
@employees
end
def get_员工
@雇员=[]
组。每个组都有| i|
@员工>>用户.查找(4).获取员工
>=>[[电子邮件地址:”test@gmail.com",
>创建于:“2010-08-25 04:23:02”,
>更新地址:“2010-08-25 04:23:02”>,
> # "hello@gmail.com“,创建于:
>“2010-08-25 04:51:37”,更新地址:
> "2010-08-25 04:51:37">]]
但是,以下代码不起作用:
>> @user.get_employees.each{|i| p i.first_name}
NoMethodError: undefined method `first_name' for #<Class:0x9e372f0>
>@user.get|u employees.each{| i | pi.first_name}
NoMethodError:未定义的方法“first_name”#
要从循环中获取
员工的名字
,我需要做什么?在我看来,变量I仍然是一个数组。您将@employee声明为空数组,并插入另一个数组,该数组是Group.find(i).employees返回的数组
i[0]应包含:
#<Employee id: 4, first_name: "test", last_name: "test1",
> email_address: "test@gmail.com",
> created_at: "2010-08-25 04:23:02",
> updated_at: "2010-08-25 04:23:02">,
> #<Employee id: 5, first_name: "hello", last_name: "hello1", email_address:
> "hello@gmail.com", created_at:
> "2010-08-25 04:51:37", updated_at:
> "2010-08-25 04:51:37">
#电子邮件地址:test@gmail.com",
>创建于:“2010-08-25 04:23:02”,
>更新地址:“2010-08-25 04:23:02”>,
> # "hello@gmail.com“,创建于:
>“2010-08-25 04:51:37”,更新地址:
> "2010-08-25 04:51:37">
Group.find(i).employees调用返回一个数组,因此您的get\u employees
方法返回一个数组。用@employees.flant替换最后一行get_employees
应该可以做到这一点。正如前面的海报所指出的,您已经在一个数组中找到了一个数组。为什么要重新创建一些已经内置在rails中的逻辑?在用户模型中,我会这样做:
class User < ActiveRecord::Base
has_many :groups
has_many :employees, :through => :groups
end
class用户:组
终止
然后你可以只做User.employees
我做不到这一点…因为我在用户模型中获取组的方式是:有很多:部门有很多:组,通过=>:部门
现在我做不到有很多:员工,通过=>:组
在这类模型中有一个类似的问题,所以:
class User < ActiveRecord::Base
has_many :groups
has_many :employees, :through => :groups
end