0

我的应用程序有两个模型 Student 和 Parent student belongs_to parent

父母有属性namecontact_no

我想做的是基于某些条件

@h=Hash.new
@students = Student.find(:condition)
@students.each do |student| 
  @h[@student.parent.contact_no] = @student.parent.contact_no+','+@student.name
end

但是哈希没有被创建。我无法理解这有什么问题。

对单个学生正常工作的代码没有循环工作

@h=Hash["@student.parent.contact_no" = @student.parent.contact_no]
4

1 回答 1

0

除非在我们看不到的地方确实@student定义了一个实例变量......很可能你打算不在@循环中使用符号。所以这个,而不是:

@students.each do |student| 
  @h[student.parent.contact_no] = student.parent.contact_no+','+student.name
end

也就是说,你可以做很多事情来清理它并加速它。我会这样做,而不是:

@students = Student.includes(:parents).where(<condition>)  # Eager load the associated parents
@h = @students.inject({}) do |acc, student|  # Initialize the new hash and loop
  acc[student.parent.contact_no] = "#{student.parent.contact_no},#{student.name}"  # String interpolation is faster than concatenation
  acc  # Return the accumulator
end

在这里,inject(有时称为reduce)将负责初始化新的哈希,然后在最后返回构建的哈希。然后,因为我们使用了关联的预先加载,parents我们不会在循环的每次迭代中进行数据库查找。最后,字符串插值 ( "#{}") 比字符串连接 ( "" + "") 更快。

于 2013-09-21T12:54:52.807 回答