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.