My application, based on the Michael Hartl's tutorial, renders in the home page a collection of the user's microposts and of the microposts of the user's following through method feed
in user.rb
:
def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id).limit(100)
end
I added a limit of 100 microposts.
Logging in the console, I checked that the limit was respected:
2.3.1 :003 > user.feed.count
(1.6ms) SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
WHERE follower_id = 1)
OR user_id = 1) LIMIT $1) subquery_for_count [["LIMIT", 100]]
=> 100
A @feed_item
variable is defined in the controller as follows:
@feed_items = current_user.feed.paginate(page: params[:page])
then it is rendered into view.
However, when I browse the page with my browser, the limit is not respected and I get all microposts (251 instead of 100, 9 pages of 30 microposts each instead of 4). Why is that?
#paginate
redefines limit and offset of the relation.
For what you want to achieve you can pass option total_entries
to #paginate
@feed_items = current_user.feed.paginate(page: params[:page], total_entries: 100)