0

i'm new to rails and i don't know how to do this simple operation :

i have ,

class Section < ActiveRecord::Base
   has_many :articles
   has_many :questions
end

class Article < ActiveRecord::Base
   belongs_to :section
end

class Question < ActiveRecord::Base
   belongs_to :section
end

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 .

Akramz
  • 23
  • 1
  • 5
  • Once you get them together out of the db into an array you can use sort the array on the updated_at or you could use group by to group by the date depending on how you plan to display the array matters. – jBeas Mar 06 '15 at 01:16

2 Answers2

0

Once the result is in a single array you can do:

@sorted = @records.sort_by &:updated_at

jBeas
  • 926
  • 7
  • 20
0

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 + operator:

articles_and_questions = section.articles + section.questions

The articles_and_questions variable is of type ActiveRecord::Associations::CollectionProxy. Because the @targets of section.articles and 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 Array:

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.

Community
  • 1
  • 1
Hélène Martin
  • 1,409
  • 2
  • 15
  • 42
  • thank you for ur help , however i still have a problem when i add up the articles and questions together how do i know which are articles or questions and access them ? , i tried doing like `- @sorted_posts.each |post|` then `= post.title` (they have a common column title) but its gives an error of : undefined method ! – Akramz Mar 06 '15 at 18:51
  • i solved it by defining a method inside each model named "type" that returns the name of the table , then setting conditions on types to know which type of post im dealing with .. i dont know if this is the optimal solution . – Akramz Mar 06 '15 at 19:26
  • I'm glad that helped! I'm afraid I can't reproduce your problem. I was able to do something like `@sorted_posts.each do |post| puts @sorted_posts.title end` in the rails console. If you do need to find out the type of each post, you can use Ruby's `instance_of?` method (`@sorted_posts.first.instance_of? Question`). – Hélène Martin Mar 06 '15 at 20:05