Combine two models in single #index action

Hi!

I’m having trouble with simple thing.
In my app (open source, repo: https://github.com/skyderby/skyderby ) 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: https://github.com/skyderby/skyderby/blob/dev/app/controllers/events_controller.rb#L10

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: https://thoughtbot.com/upcase/videos/intermediate-part-3. 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