0

Im trying to get all the Posts from the the Users. I'm following using the act_as_follower gem. The User follows a profile model, and Posts belong to a User.

My User model:

  acts_as_follower

My Profile model the user follows:

  belongs_to :user
  acts_as_followable

Post model:

  belongs_to :user

My Post Controller.rb:

  def follow
    @profile = Profile.find(params[:id])
    current_user.follow(@profile)
    redirect_to :back
  end

  def unfollow
    @profile = Profile.find(params[:id])
    current_user.stop_following(@profile)
    redirect_to :back
  end

Im trying to implement something like this using follows_by_type method provided:

@posts = current_user.follows_by_type('Post').order("created_at DESC")

But the thing is the User follows the Profile model, but here I'm looking for a type 'Post'.

EDIT

In my index controller i'v set up the following:

@favoritePost = Post.where(user_id: current_user.all_follows.pluck(:id))

And in the view iv implemented this:

<% if user_signed_in? %>
   <%@favoritePost.each do |post| %>
      <%= post.title %>
   <% end %>
<% end %>
Gurmukh Singh
  • 1,875
  • 3
  • 24
  • 62

2 Answers2

2

The gem lets you follow multiple models and follows_by_type('Post') filters the Posts you follow.

What you're looking to do is to return the posts from the users you follow.

Controller

@posts = Post.where(user_id: current_user.all_following.pluck(:id))

View

<% @posts.each do |post| %>
  <%= post.title %>
<% end %>
Hass
  • 1,628
  • 1
  • 18
  • 31
  • Would i need to add `acts_as_followable` to my Post model? – Gurmukh Singh Jan 10 '17 at 08:44
  • @GurmukhSingh you don't need to because you're not following the post, just the user. – Hass Jan 10 '17 at 13:44
  • I'm getting undefined method `all_follows' for nil:NilClass – Gurmukh Singh Jan 10 '17 at 17:36
  • @GurmukhSingh so you don't have `current_user` Are you signed in? – Hass Jan 11 '17 at 07:43
  • @GurmukhSingh you should also put the check for signed in user in your controller `@favoritePost = Post.where(user_id: current_user.all_follows.pluck(:id)) if current_user` – Hass Jan 12 '17 at 04:54
  • @hussainAhmed, i tried this solution but i get a `cant load polymorphic relation error`, Iv worked out a solution, is it ok to leave this logic in the controller or shift it to the model? if so how could i shift it to the model? – Gurmukh Singh Jan 13 '17 at 09:10
0

I worked out this solution, might not be the best, but it works as required.

In my controller i set this up:

@following = current_user.all_following
@followposts = @following.each do |f|
  f.user.id
end

And in my view I have set this up:

<% @followposts.each do |f| %>
  <% f.user.posts.each do |g| %>
    <%= g.title %>
  <% end %>
<% end %>
Gurmukh Singh
  • 1,875
  • 3
  • 24
  • 62