Sergio Guerrero Sergio Guerrero - 10 months ago 42
Ruby Question

Ruby Rails Loop in Controller

I have a controller that I want to use to generate reports from, my first report works fine it's simply a sorted output of my CSEmployee table. However my second report isn't giving me what I would expect. Each CS_Employee can have multiple time_entries in the TimeEntry table associated with it. I have indexed the table and created a has_many\belongs_to relationship and all seems to work just fine in my other views. My second report needs to show all associated time_entries for each CS_Employee for a given time period. Here is what I have so far:

def cs_employees
@cs_employees = CsEmployee.all
@cs_employee = @cs_employees.order(:cs_name)
respond_to do |format|
format.csv { send_data @cs_employee.to_csv }
format.xlsx #{ send_data @cs_employee.to_csv(col_sep: "\t") }

def schedules
@start_date = params[:start_date] || 2.weeks.ago
@end_date = params[:end_date] ||
@cs_employee = CSEmployee.all
@cs_employees.each do |cs_employee|
@cs_employee = cs_employee.find(params[:cs_employee_id])
@time_entries = @cs_employee.time_entries.find(params[:id])
@time_entries.each do |time_entry|
tschedules = time_entry.where(:date => (params[:start_date]).to_date..(params[:end_date]).to_date)
@schedules += tschedules if tschedules

When I try to Debug for @schedules there is nothing in the variable. Any help would be appreciated.


You do not seem to be populating your @cs_employees variable when you call @cs_employees.each

Also, there is way too much business logic in your controller. Move it to your model or a concern.