i'm new to rails and i don't know how to do this simple operation :
i have ,
class Section < ActiveRecord::Base
class Article < ActiveRecord::Base
class Question < ActiveRecord::Base
and i want to get all articles and questions under a certain section but sorted together by shared column 'updated_at' .
i tried including and joining them but failed to order them together .
Best How To :
Start by finding the section that you wish to work with. For example, you could find a particular section by ID (12 in this case):
section = Section.find(12)
You can then access the articles and questions that belong to that section and combine the results with the
articles_and_questions = section.articles + section.questions
articles_and_questions variable is of type
ActiveRecord::Associations::CollectionProxy. Because the
section.questions are both
Arrays of objects, you can call any method from the
Array class on
articles_and_questions. In this case, you can use
sort_by which comes from the
Enumerable module included in
sorted_articles_and_questions = articles_and_questions.sort_by &:updated_at
If you want to know why there's an ampersand in
&:updated_at, read this.