为什么在视图中不尊重限制方法?
Why limit method is not respected in view?
我的应用,基于Michael Hartl的教程,在首页渲染了用户的微博和用户通过user.rb
方法feed
关注的微博集合:
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
我添加了100条微博的限制。
登录控制台,我检查了限制是否得到遵守:
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 ) subquery_for_count [["LIMIT", 100]]
=> 100
一个@feed_item
变量在控制器中定义如下:
@feed_items = current_user.feed.paginate(page: params[:page])
然后渲染到视图中。
但是,当我使用浏览器浏览页面时,没有遵守限制,我得到了所有微博(251 个而不是 100 个,9 页,每页 30 个微博,而不是 4 个)。这是为什么?
#paginate
重新定义关系的极限和偏移量。
对于您想实现的目标,您可以将选项 total_entries
传递给 #paginate
@feed_items = current_user.feed.paginate(page: params[:page], total_entries: 100)
试试这个
@feed_items = current_user.feed.paginate(page: params[:page], per_page: 30, total_entries: 100)
我的应用,基于Michael Hartl的教程,在首页渲染了用户的微博和用户通过user.rb
方法feed
关注的微博集合:
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
我添加了100条微博的限制。
登录控制台,我检查了限制是否得到遵守:
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 ) subquery_for_count [["LIMIT", 100]]
=> 100
一个@feed_item
变量在控制器中定义如下:
@feed_items = current_user.feed.paginate(page: params[:page])
然后渲染到视图中。
但是,当我使用浏览器浏览页面时,没有遵守限制,我得到了所有微博(251 个而不是 100 个,9 页,每页 30 个微博,而不是 4 个)。这是为什么?
#paginate
重新定义关系的极限和偏移量。
对于您想实现的目标,您可以将选项 total_entries
传递给 #paginate
@feed_items = current_user.feed.paginate(page: params[:page], total_entries: 100)
试试这个
@feed_items = current_user.feed.paginate(page: params[:page], per_page: 30, total_entries: 100)