Hopstream
Hopstream

Reputation: 6451

Rails how to sort based on "last activity" using a model and it's has_many association?

I have two models:

Question:
   has_many: answers

Answer:
   belongs_to: question

How can I select all questions ordering based on "last activity" which would be the question.created_at or answer.created_at

Examples:

If an old question just got a new answer, it would be the first one on the list.

If a new question just got posted, it would be the first one on the list.

Upvotes: 0

Views: 113

Answers (2)

junil
junil

Reputation: 768

You can add another field for questions which would be set to the current time each time a new answer is added to the question.The initial value should be set same as created at.then sort them based on this column

Upvotes: 1

Mohamed Yakout
Mohamed Yakout

Reputation: 3046

Try this code:

Make scope in Question Model

scope :sorted_questions, order("id DESC")
scope :sorted_answers, order("answers.created_at DESC")
scope :final_sorted, order("id DESC, answers.created_at DESC")

Then try this:

@questions = Question.sorted_answers
index = 0
@quesions.each do |question|
  if question.id != Quesion.sorted_questions[index].id
     index++
  else
     break
  end
end
@questions << Quesion.sorted_questions[0...index]

or Try this:

@questions = Question.final_sorted

Efficient sorting of rows by multiple columns in Rails 3

Upvotes: 2

Related Questions