[英]How can I iterate through a model then iterate again in my view?
I want to pull data for each of my users.我想为我的每个用户提取数据。 I grab their person_id
from my user table, then use each person's ID to figure out how many days each person has available, and show that in my view.我从我的用户表中获取他们的person_id
,然后使用每个人的 ID 来计算每个人有多少天可用,并在我的视图中显示。 I'm not sure if I am doing this correctly because I am iterating in my controller then again in my view.我不确定我是否正确执行此操作,因为我正在控制器中进行迭代,然后在我的视图中再次进行迭代。
def how_many_days_users_have
@my_group = User.all.pluck(:person_id)
@my_group.each do |v|
@indirect_id_v = Empaccrl.where("person_id = ? and is_active = ?", '#{v]', 'Y').pluck(:a_code).first
@v_range = Empaccrl.where("person_id = ? and is_active = ?", '#{v]', 'Y').pluck(:ac).first
@v_range_taken = Empaccrl.where("person_id = ? and is_active = ?", '#{v]', 'Y').pluck(:taken).first
@total_v_hours = @v_range.to_d - @v_range_taken.to_d
@total_v_days = @total_v_hours / 8
end
Then in my view I use this to show me this data:然后在我看来,我用它来向我展示这些数据:
%tr.trace-table
-@indirect_id_v.each do |idd|
%tr.trace-table
%td.trace-table{:style => 'border: solid black;'}= idd
-@total_v_days.each do |days|
%tr.trace-table
%td.trace-table{:style => 'border: solid black;'}= days
Okay, first things first, move some of that junk to your model, like so:好的,首先,将一些垃圾移动到您的模型中,如下所示:
class Empaccrl < ActiveRecord::Base
def self.all_people
where(person_id: User.all.pluck(:person_id))
end
def self.active_people
all_people.where(is_active: 'Y')
end
def self.active_vacation_data
active_people.select(:person_id, :ac, :taken)
end
def total_v_hours
ac.to_d - taken.to_d
end
def total_v_days
total_v_hours / 8
end
end
Then you can use:然后你可以使用:
peoples_vacation_information = Empaccrl.active_vacation_data.all
peoples_vacation_information.map do |person|
p "person #{person.person_id} has #{person.total_v_days} vacation days"
end
Honestly, you don't even need all that, but I'm not sure why you are doing what you are doing, so I figured better be safe and add stuff.老实说,您甚至不需要所有这些,但我不确定您为什么要这样做,因此我认为最好确保安全并添加一些东西。 Whatever you don't need, just ignore.不需要的,直接无视。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.