Annette
Annette

Reputation: 317

Incorrect user posts being displayed. (Follower & Following)

I am trying to display posts from users I am following. However, for some reason my stream index is displaying posts from users who are following me. How can I display posts from users I am following and not the other way around? Thank you in advance.

User Model

has_many :following, :through => :relationships, :source => :followed
has_many :subscribed, class_name: "Relationship", foreign_key:  "follower_id"

Post Model

scope :subscribed, ->(following) { where user_id: following }

Relationships Model

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
  validates :follower_id, presence: true
  validates :followed_id, presence: true

  has_many :followed_users, through: :relationships, source: :followed

  #fields id | user_id | follower_id | created_at | updated_at
  belongs_to :user
end

Stream Controller

class StreamController < ApplicationController
  def index
    @posts = Post.subscribed current_user.following 
  end 
end

Stream Index

<div class="page-header">
  <center><strong><h1> Stream Page </h1></strong></center>
</div>

 <div id="posts" class="transitions-enabled">
  <% @posts.each do |post| %>

    <div class="box panel panel-default">
      <%= link_to image_tag(post.image.url(:medium)), post %>
      <div class="panel-body">
      <%= post.description %><br/>
      <strong><%= post.user.name if post.user %></strong>
     <% end %>
    </div>
    <% end %>
    </div> 
  <% end %>
 </div>

Upvotes: 1

Views: 50

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

The problem will be with the association you're calling

--

Associations

You're using my code (which is great!!) - I think the problem will be how you're calling the relationship association data

You'll be able to do this:

#app/controllers/posts_controller.rb
Class PostsController < ApplicationController
   @posts = Post.subscribed current_user.followed 
end

Upvotes: 1

Related Questions