【问题标题】:Rails sort by count and time of a join tableRails 按连接表的计数和时间排序
【发布时间】:2014-04-10 18:32:56
【问题描述】:

我正在为我的活动模型使用acts_as_votable,并且我已经能够使用以下代码仅选择对其投票的活动:

@activities = Activity.select("activities.*, COUNT(votes.id)").joins(:votes).group("activities.id").order("created_at desc").page(params[:page]).per_page(72)

但是我如何选择只有超过 3 票的活动以及仅在上个月内创建的活动?

有谁知道我怎么能做到这一点?提前致谢。

【问题讨论】:

    标签: ruby-on-rails rails-activerecord jointable voting


    【解决方案1】:

    例如,

    Client.where("orders_count = ?", params[:orders])
    

    Activity.where("votes.id > ? and created_at > ?", 3, beginning_of_month*)
    

    另外,“Chapter 2: Conditionals”可能对您有用!

    *http://apidock.com/rails/DateAndTime/Calculations/beginning_of_month

    【讨论】:

    • 谢谢,但如果我在这样的地方使用它会抛出 SQLException: no such column: votes: 加上该代码给出另一个错误:syntax error, unexpected ')'
    【解决方案2】:

    having 是我想要的。比如:

    @activities = Activity.joins(:votes).group("activities.id").having("count(votes.id) >= ?", 1).order("created_at desc").where(:created_at => 6.months.ago..Time.zone.now.to_date).page(params[:page]).per_page(60)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2019-11-01
      相关资源
      最近更新 更多