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.
#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"
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