以DESC顺序连接查询关联模型

时间:2013-08-23 11:22:44

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

问题模型has_many答案。如何计算答案数量问题并在DESC命令中相应地进行排序?我使用连接方法。

我怎样才能提出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 gem。如何将.ransack(params [:q])添加到@questions数组?

1 个答案:

答案 0 :(得分:0)

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

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

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

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

相关问题