[Rails] List instances of multiple models

What you want to do

Like the YouTube and Facebook timelines, we needed the ability to display posts and ads on the same screen in descending order of creation (usually ads may not be in order of creation, but to keep things simple. (Assuming that they are arranged in the order of creation).

Let's think about how to get the post model (Post) and the advertisement model (Advertisement) well with the controller and process them in parallel in the view.

Premise

version

Columns of each model

#Posting model and advertising model have different columns

#Post model (Post)
  t.integer "user_id"
  t.string "content"
  t.string "image"
  t.datetime "created_at"
  t.datetime "updated_at"

#Advertising model (Advertisement)
  t.integer "company_id"
  t.string "content"
  t.string "link_url"
  t.datetime "expired_date"
  t.datetime "created_at"
  t.datetime "updated_at"

Implementation method

timeline_controller.rb


def index
  posts = Post.all
  ads = Advertisement.all

  #Make each multiple instance into one array
  @instances = posts | ads
  #Sort in descending order of creation
  @instances.sort!{ |a, b| b.created_at <=> a.created_at }
end

erb:index.html.erb


<% @instances.each do |instance| %>
  <% if instance.class == "Post" %>
    <%#Post display%> 
    <%= instance.user_id %>
    <%= instance.content %>
    <%= instance.image %>
  <% else %>
    <%#Display Advertisement%> 
    <%= instance.company_id %>
    <%= instance.content %>
    <%= instance.link_url %>
  <% end %>
<% end %>

Recommended Posts

[Rails] List instances of multiple models
[Rails] Manage multiple models using devise gem
[rails] List of actions defined in Controller
[Rails 6.0] About batch saving of multiple records
[Note] Rails error list
[Rails] Introduction of PAY.JP
List of beginners (List) memo
Rails Tutorial/Significance of Indexing
[Rails] Volume that displays favorites and a list of favorites
Registration of multiple WebMvcConfigurers
[Rails 6] Rubocop warning list
[Rails] Put the same restrictions on multiple pieces of information
Delete all the contents of the list page [Ruby on Rails]
[Rails] How to display the list of posts by category
Rails implementation of ajax removal
[Rails] Introduction of devise Basics
docker-compose command list (for Rails)
Utilization of Rails Boolean type
[Rails 6] Implementation of search function
[Rails] Implementation of category function
Use devise on multiple models
Use multiple databases with Rails 6.0
[Ruby] List of basic commands
[Rails] Implementation of tutorial function
Use multiple checkboxes in Rails6!
[Rails] Implementation of like function
List of hosts file locations