MAC MAC - 4 years ago 85
Ruby Question

How to query data using rails?

I wanted to query data using between clause like this

select * from timerecords where empid=? and date between ? and ?

I just have to do it in rails. I have this code and I want the program to display in json format redirecting to localhost/timerecords.

def showtimerecords
enddate =params[:date]

render json: @timerecords=Timerecords.where(empid: empid,
:date => startdate..enddate)
#redirect_to @timerecords

When I type http://localhost:3000/timerecords/showtimerecords/empid=2&startdate=2015-03-26&enddate=2015-03-27

It says,

(No route matches [GET] "/timerecords/showtimerecords/empid=2&startdate=2015-03-26&enddate=2015-03-27")

Here's my config/route.rb code

Rails.application.routes.draw do
get 'timerecords/showtimerecords'
get 'timerecords/index'
get 'employees/index'
get 'employees/show'
get 'employees/new'
get 'welcome/index'
root :to => 'employees#new'
resources :timerecords, :employees
post 'employees/update_info'
post 'timerecords/update_time'

Answer Source

You are typing it wrong, it should look like this, the parameters should start with a ?, try using the following link


Also, you are sending startdate and enddate parameters but you are accessing using date, modify your code as mentioned below

def showtimerecords
   enddate =params[:enddate].to_date

   @timerecords = Timerecords.where(empid: empid,
                                :date => startdate..enddate) 

   render json: @timerecords
   redirect_to 'timerecords/index'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download