Topic: Prob w/ displayng all of the posts of user and the ones he's following

Can u please help me cos I can't display the user's posts and the one's he is following. I have tried out all of the possible codes but still it doesn't work here's my current code for my site_controller.rb.

#site_controller.rb
def index {
@title = "Index  | Baby"
@friendship = Friendship.find(:all, :conditions => {"user_id" => current_user})
@posts = Post.find(:all, :conditions => {"user_id" => @friendship.friend_id})
@users = User.find(:all, :conditions => {"user_id" => @friendship.friend_id})
}

This code always gives me an error undefined method friend_id.

Am I doing the right way. Please help me. I am stuck in this part. . .

XOXO

Re: Prob w/ displayng all of the posts of user and the ones he's following

I think the problem is that your query on Friendship will return a collection, not a single friendship. Therefore, you're trying to send friend_id to a collection. That's where the undefined method is coming from (in the future, put the exact error in the question smile.

I'm going to make some assumptions about how you've defined your models, but here are some suggestions to get you moving. None of this code has been executed, I'm typing it straight in here...

user.rb

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships, :class_name => 'User'
end

Assumes friendships is a join table for a self-referential relationship on User.

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
  named_scope :by_users, lambda { |user_ids| { :conditions => ["posts.user_id in (?)", user_ids] } }
end

At that point, it should be easy to get the user's friends and then select all of the posts from those users.

sites_controller.rb

def index
  @title = "Index | Baby"

  # Find all of this user's friends
  @users = User.friends

  # Find all of the posts from this user's friends
  @posts = Post.by_users(@users.collect(&:id))
end

Hopefully that will help get things going... Good luck!

I'm a Phoenix Ruby on Rails developer and startup junkie kicking ass at Flatterline, a Ruby on Rails web application development company.

Re: Prob w/ displayng all of the posts of user and the ones he's following

Your code gave me an error: undefined method `friends'.

This is what I did in my display page:


<h1>Merry Christmas Little Monsters</h1>
<%= link_to "Make Friends", users_path %> 

<%users.each do|u| %>
<%= u.login %>
<% @posts.each do |p| %>
  <%= p.body %>
<% end %>
<% end %>

Thank you so much. . . Though. . . Thank you. . .