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 trialRyan Ellis
864 PointsHow do I filter posts in Rails 4 with a scope based off a nested attribute?
I need to filter the posts that appear on my index page. I filtered them initially by using this condition in the view:
if current_user.courses.any? {|h| h[:name] == post.course.name}
But since I added will_paginate, I get blank pages because it paginates even the posts I don't want to show. How can I use a scope to filter out the posts in the controller?
These are my models:
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :course
has_many :comments
end
and
class Course < ActiveRecord::Base
belongs_to :user
has_many :posts
belongs_to :major
end and my controller codes
def index
@posts = Post.all.order("created_at DESC").paginate(:page =>
params[:page], :per_page => 1)
end