Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Zander Perry
2,227 PointsBest way to scope Statuses to User's friends?
Hey folks,
I've been trying to scope the status feed in statuses#index to show statuses from the current_user's friends.
I was able to create an array of current_user's friends called @contacts. @statuses = @contacts.statuses.all just leads to a NoMethodError for 'statuses' - so I'm wondering if I'm going to need to:
- Iterate the statuses for each user in the @contacts array
- Push those to another big array (@friends_statuses for example)
- Order them by :created_at
- Iterate each status from the new @friends_statuses array (in the view)
Can anybody think of a way that's a little more efficient?
Existing Statuses Controller
def index
@user_friendships = current_user.user_friendships.all
@user_friendships.each do |friendship|
friend = friendship.friend
@contacts ||= Array.new
@contacts.push(friend)
end
@statuses = Status.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @statuses }
end
Thanks!
Zander
1 Answer
Zander Perry
2,227 PointsFigured it out!
def index
@user_friendships = current_user.user_friendships.all
@user_friendships.each do |friendship|
friend = friendship.friend
@contacts ||= Array.new
@contacts.push(friend)
end
@contacts.each do |x|
x_statuses = x.statuses.all
x.statuses.each do |stat|
# puts stat.activity <- just to see things are going through
@friend_statuses ||= Array.new
@friend_statuses.push(stat)
end
end
# puts @friend_statuses
@statuses = @friend_statuses
respond_to do |format|
format.html # index.html.erb
format.json { render json: @statuses }
end
end