Title: joins query for associated model in DESC order
Tags: ruby-on-rails-3;activerecord;join
Question: Question model has_many Answer. How to count amount of answers question has and order accordingly in DESC order? I use joins method.
How could I make the most answered questions DESC order?
UPDATED
Here is how to make the most answered question DESC order:
@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| %&gt;
<%= question.answers_count %&gt;
<%= end %&gt;
I have another issue now. I use ransack gem. How do I add .ransack(params[:q]) to @questions array?


Here is another answer: if params[:q] is what tells you how many answers a question has, I think you could do
Question.tagged_with(params[:tag]).joins(answers: :user).uniq.ransack(params[:q]).order("params[:q] DESC")
But that's not tested, so not sure.  check out the documentation on ordering here and you should be able to get it!
You can also put the results of that query in your original post, that will help to figure it out if this doesn't work.
Comment for this answer: don't know much about ransack, sorry!
Comment for this answer: Thanks for respond! Maybe you could look at updated question and suggest something? I found how to make answered questions in DESC order, however can't grasp how to add .ransack(params[:q]) to the @questions array.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:08/23/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ruby-on-rails-3><activerecord><join>', 'Title': 'joins query for associated model in DESC order', 'ViewCount': 72, 'id': 18401592, 'user_AboutMe': '', 'user_AccountId': 2843505.0, 'user_DisplayName': 'vitdes', 'user_Reputation': 124.0, 'user_Views': 66.0, 'user_id': 2442553.0}}