0

I am new to ruby on rails and am trying to write a rest api for an employee timesheet service for class. I am having trouble selecting timesheets based on their date and sending back the json.

Here is my code:

before_filter only: :index do
parse_request
unless @json.has_key?('timesheet') && @json['timesheet']['year'] && @json['timesheet']['month']
  render nothing: true, status: :bad_request
end
end

def index
year = @json['timesheet']['year']
month = @json['timesheet']['month']
if(@json.has_key?(:day))
  week = @json['timesheet']['day']
  begin_date = DateTime.new(year, month, day, 00, 00, 00)
  end_date = begin_date + 1.week + 1.day
else
  begin_date = DateTime.new(year, month, 01, 00, 00, 00)
  end_date = begin_date + 1.month + 1.day
end
if(params.has_key?(:employer_id))
  render json: Timesheet.where(employer_id: params[:employer_id], time: begin_date..end_date)
elsif(params.has_key?(:employee_id))
  render json: Timesheet.where(employee_id: params[:employee_id], time: begin_date..end_date)
else
  render nothing: true, status: :bad_request
end

Here are my relevant routes:

scope '/:employer_id' do
          get '/' => 'api_employers#show'
          put '/' => 'api_employers#update'
            scope '/timesheets' do
              put '/' => 'api_timesheets#index'
            end

and

scope '/:employee_id' do
        get '/' => 'api_employees#show'
        put '/' => 'api_employees#update'
          scope '/timesheets' do
            put '/' => 'api_timesheets#index'
            post '/' => 'api_timesheets#create'

I try to get the timesheets with the following command in terminal:

curl -H "Content-Type: application/json" -X PUT -d '{"timesheet":{"employer_id":"1", "employee_id":"1", "year":"2016", "month":"3"}' http://tester-1234.herokuapp.com/api/v1/employees/1/timesheets

but it renders nothing. The reason I check for the day param in index is because if the user specifies a day, it should return timesheets for a week from that day, and if they do not, it should just return timesheets for the whole month. Any help is much appreciated.

Jared
  • 578
  • 7
  • 21
  • I would put a pry in the controller and see if the code goes through the action as expected https://github.com/pry/pry – Petr Gazarov Mar 30 '16 at 01:11
  • @PetrGazarov: is there no way i can do a simple "print" statement or anything like that? – Jared Mar 30 '16 at 01:13
  • I don't think there is an easy way to print something back to the terminal because then you would have to actually be sending a response, which is what you are having trouble with in the first place. That said, if you are testing for JSON response, try this handy tool: https://www.getpostman.com/ – Petr Gazarov Mar 30 '16 at 01:42
  • Possible duplicate of [How to debug using rails console and puts in application](http://stackoverflow.com/questions/26711173/how-to-debug-using-rails-console-and-puts-in-application) – Paul Sweatte Oct 21 '16 at 06:15

0 Answers0