0

I have a class, Teacher, that has multiple integer columns:

t.integer :a_students
t.integer :b_students
t.integer :c_students
t.integer :d_students
t.integer :f_students

And I have a view that loops through all the teachers and states how many students are in their class. Now although I could add all the students in the view, just to make it look nicer I want to offload adding all the students into the model. I have the following model method:

  def count_students( teacher_id )
    t = Teacher.find(teacher_id)
    total = t.a_students + t.b_students + t.c_students + t.d_students + t.f_students
    total
  end

If I'm not mistaken, I shouldn't be accessing model methods from the view - that should be left to the controller. But since its looping through, I'm a little lost on what to do in this case. Any Ideas?

Thanks Ben

4

4 回答 4

3

在您的教师模型中,有一个类似这样的方法:

def total_students
  a_students + b_students + c_students + d_students + e_students + f_students
end

然后在您看来,如果您有 t,一位特定的老师,您只需执行 t.total_students 即可获得您想要的总数。

于 2013-02-05T08:09:37.923 回答
2

教师模型类中的该方法将是一个实例方法。因此,您无需致电数据库即可找到老师,因为您已经拥有该信息:

def count_students
    total = a_students + b_students + c_students + d_students + f_students
end

您还可以使用self. Ruby 还返回最后计算的值,因此您不需要最后的总计。

于 2013-02-05T08:07:37.153 回答
1

为什么不把你的代码移到你的控制器上,为什么你有这么多不同的学生呢?

如果您想从特定老师那里收集所有学生,这将是:

@teacher = Teacher.find(params[:teacher_id])
@students = @teacher.students.all

但是,嘿,也许我只是误解了你的问题。

于 2013-02-05T08:10:14.207 回答
0

在您的控制器中,您应该执行任何中间逻辑。这个循环的目的是什么?它是否返回总价值?如果是这样,为什么不能在控制器中执行此操作并将操作结果返回给视图?

于 2013-02-05T08:07:28.977 回答