Combine two models in single #index action

Hi!

I’m having trouble with simple thing.
In my app (open source, repo: GitHub - skyderby/skyderby: The most advanced flight analysis and competition scoring ) I have two different types of events with different structure.
It is Event (actually competition) and Tournament.
And there should be one index page for both of it.

Now it’s achieving by:

  tournaments = Tournament.includes(place: :country).all.to_a
  events = EventsFinder.new.execute(current_user).to_a

  @events = (tournaments + events).sort_by { |x| x.starts_at }.reverse

link: skyderby/events_controller.rb at dev · skyderby/skyderby · GitHub

I know that it is wrong, but don’t know how to do it right. So if I need to combine two models in one list - what is a good approach for it(View (scenic), Finder class, something else)?

P.S. Please have in mind, that I started to write app with 0 knowledge about web development at all without any mentor (still do not have one).

The Intermediate Rails trail has a section about using multiple models in an action. The discussion starts at the 14:00 mark in this video: Part 3 | Online Video Tutorial by thoughtbot. Hope that helps!

Thank you! That will definitely work!

I want to share how I made it solved a bit simpler, as I think. I use scenic gem, so I created view with UNION of both tables, created model for this view and using this model now.

1 Like