I am using c9 cloud ruby on rails and my Rails version is 5.0.0.1
I want to compose an ActiveRecord query to select the restaurant with the best rating which has not been visited yesterday. When I applied all
where
, order
and first
in the query, it throws an error. However, if I don't use where
or order
, it works fine.
This works:
restaurant1= Restaurant.order('rating').last!
@suggested_restaurants=restaurant1.name
This gives strange results:
restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}
@suggested_restaurants=restaurant1
Results: #<ActiveRecord::QueryMethods::WhereChain:0x000000046af7f8>
This triggered error:
restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}.last
@suggested_restaurants=restaurant1
Error: undefined method 'last' for #ActiveRecord::QueryMethods::WhereChain:0x00000004587a10>
I can get around this issue by using find_by_sql
but I'd like to know why and how to use where
in Rails 5. Thanks a lot!
try this:
restaurants = Restaurant.where('last_visit < ?', Date.yesterday).order({ rating: :asc })
this gives you a collection of restaurants matching your constraints passed in where
method, the result of which is chained to order
method that orders the collection in ascending order of the values in rating
column of restaurants
table. use :desc
if you want to order in descending order.
Then, you can retrive last object with
restaurant1 = restaurants.last