如何使用rails查询数据?

How to query data using rails?

我想像这样使用 between 子句查询数据

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

我只需要在 rails 完成。我有这段代码,我希望程序以 json 格式显示重定向到 localhost/timerecords.

  def showtimerecords
   empid=params[:empid]
   startdate=params[:date]
   enddate =params[:date]

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

当我键入 http://localhost:3000/timerecords/showtimerecords/empid=2&startdate=2015-03-26&enddate=2015-03-27

它说,

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

这是我的 config/route.rb 代码

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'
end

你打错了,应该是这样的,参数应该以?开头,试试下面的link

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

此外,您正在发送 startdateenddate 参数,但您正在使用 date 进行访问,请按以下所述修改您的代码

def showtimerecords
   empid=params[:empid]
   startdate=params[:startdate].to_date
   enddate =params[:enddate].to_date

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

   render json: @timerecords
   redirect_to 'timerecords/index'
end