0

我有一个返回多个属性的学生数组对象。我只需要从这个数组中提取特定的属性。这是我尝试过的代码

@project.each do |p|
          @students << Student.find_by_id(:id => p.receiver_id, :select => "first_name, last_name")
        end

但它显示未知键:id。我只需要在@students 数组中插入名字和姓氏。我正在使用 rails 2.3 和 ruby​​ 1.8.7。请帮忙。

4

1 回答 1

1

You are getting that error because it should be:

@project.each do |p|
  @students << Student.find_by_id(p.receiver_id)
end

If you only want the first names and last names, then you might consider:

@project.each do |p|
  student = Student.find_by_id(p.receiver_id)
  @students << { :first_name => student.first_name, :last_name => student.last_name }
end

If you want an array, then:

@project.each do |p|
  student = Student.find_by_id(p.receiver_id)
  @students << [student.first_name, student.last_name ]
end

The first version would give you an array of hashes. The second version would give you an array of arrays.

于 2013-08-26T16:50:23.353 回答