0

Just stumbled upon this problem. I had a newsfeed that displayed a post. Containing a title and it's content. However now I added a new feature which is the comments model. Thus the keys saved in the activities table are no longer just 'post.create' but also 'comment.create'.

The problem arises when I call:

<li><strong><%= activity.trackable.title %></strong></li>

because usually it just find that the trackable is a post. Now it also has comments and the comments model has no title, thus it returns an error.

My question is how do I make it so that I can only call the 'post.create' part or a 'trackable_type' that == 'Post'.

This way I can only show the posts in the newsfeed.

sja
  • 347
  • 1
  • 10

2 Answers2

0
<% if activity.trackable.title %>
  <li><strong><%= activity.trackable.title %></strong></li>
<% end %>

Of course, you could also show different type of activities, defining the text to render for each model and action.

One of Ryan Bates' railscasts describes how to do this: http://railscasts.com/episodes/406-public-activity

NicoFerna
  • 603
  • 3
  • 11
0

You don't need to call

= activity.trackable.title

You can simply do

= activity.trackable

If you need to see what's inside activity.trackable, simply inspect it like

= activity.trackable.inspect

You will then see the object that is being tracked. Like this:

#<Post id: 220, title: "Another Post", body: nil, created_at: "2021-10-03 19:51:12.391681000 +0000", updated_at: "2021-10-03 19:51:12.397088000 +0000", user_id: 1, slug: "another-post", published: false>
drjorgepolanco
  • 7,479
  • 5
  • 46
  • 47