【问题标题】:active record query order where first活动记录查询顺序 where first
【发布时间】:2016-11-30 15:52:26
【问题描述】:

我在 rails 上使用 c9 cloud ruby​​,我的 Rails 版本是 5.0.0.1

我想编写一个 ActiveRecord 查询来选择昨天没有去过的评分最高的餐厅。当我在查询中应用allwhereorderfirst 时,它会引发错误。但是,如果我不使用whereorder,它可以正常工作。

这行得通:

restaurant1= Restaurant.order('rating').last!
@suggested_restaurants=restaurant1.name

这会产生奇怪的结果:

restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}
@suggested_restaurants=restaurant1

结果: #&lt;ActiveRecord::QueryMethods::WhereChain:0x000000046af7f8&gt;

此触发错误:

restaurant1=Restaurant.order('rating').where{last_visit<Date.yesterday}.last
@suggested_restaurants=restaurant1

错误: undefined method 'last' for #ActiveRecord::QueryMethods::WhereChain:0x00000004587a10&gt;

我可以通过使用 find_by_sql 来解决这个问题,但我想知道为什么以及如何在 Rails 5 中使用 where。非常感谢!

【问题讨论】:

    标签: ruby-on-rails rails-activerecord where-clause ruby-on-rails-5 active-record-query


    【解决方案1】:

    试试这个:

    restaurants = Restaurant.where('last_visit < ?', Date.yesterday).order({ rating: :asc })
    

    这为您提供了与您在where 方法中传递的约束条件相匹配的餐厅集合,其结果链接到order 方法,该方法按照restaurantsrating 列中的值的升序排列集合桌子。如果要按降序排序,请使用:desc

    然后,您可以检索最后一个对象

    restaurant1 = restaurants.last
    

    【讨论】:

    • 结果好多了:#<0x00000003e1aea8>
    【解决方案2】:

    这会给你Relation今天没有去过的餐馆,然后你可以打电话给.last

    restaurant1 = Restaurant.order('rating').where('last_visit<?', Date.yesterday).last
    @suggested_restaurants=restaurant1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-10
      • 1970-01-01
      • 2013-06-23
      • 2015-04-16
      • 2012-08-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多