【问题标题】:joins query for associated model in DESC order以 DESC 顺序连接关联模型的查询
【发布时间】:2013-08-23 11:22:43
【问题描述】:

问题模型 has_many 答案。如何按 DESC 顺序计算问题的答案数量并相应排序?我使用joins方法。

我怎样才能使回答次数最多的问题 DESC 排序?

更新

以下是如何将回答最多的问题 DESC 排序:

@questions = Question.find(:all,
                           joins: :answers,
                          select: ' "questions".*, count("answers".id) as answers_count', 
                          group: '"questions".id',
                          order: "answers_count DESC")

查看

<% @questions.each do |question| %>
<%= question.answers_count %>
<%= end %>

我现在有另一个问题。我使用洗劫宝石。如何将 .ransack(params[:q]) 添加到 @questions 数组?

【问题讨论】:

    标签: ruby-on-rails-3 activerecord join


    【解决方案1】:

    如果params[:q] 告诉你一个问题有多少个答案,我想你可以这样做

    Question.tagged_with(params[:tag]).joins(answers: :user).uniq.ransack(params[:q]).order("params[:q] DESC")
    

    但这没有经过测试,所以不确定。查看有关订购here 的文档,您应该可以得到它!

    您也可以将该查询的结果放在您的原始帖子中,如果这不起作用,这将有助于弄清楚。

    【讨论】:

    • 感谢您的回复!也许您可以查看更新的问题并提出建议?我找到了如何按 DESC 顺序回答问题,但不知道如何将 .ransack(params[:q]) 添加到 @questions 数组。
    • 对洗劫不太了解,抱歉!
    猜你喜欢
    • 2016-05-09
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多