我正在为 rails 3 中看似简单的偏移/限制分页查询而苦苦挣扎。
班上:
class Topic < ActiveRecord::Base
set_primary_key "thread_id"
set_table_name "threads"
belongs_to :forum_board
belongs_to :user
has_many :posts, :foreign_key => "thread_id", :dependent => :destroy
attr_accessible :board_id, :title, :modified_date, :status, :post_count, :user_id, :posts_attributes
accepts_nested_attributes_for :posts, :allow_destroy => :true
attr_accessor :board_title, :admin_mode, :orig_page_number, :page_number,
:per_page, :last_page, :ban_list
查询是这样的:
Topic.includes(:posts, :user).where("threads.thread_id=? and messages.status=2", thread_id).order("messages.pdate").limit(per_page).offset(offset).first
难题是,每当偏移量> 1 时,结果都是空的。例如,limit=5、offset=5(有 20 行可用)失败。
我还看到以下 SQL 在子表上的查询之前运行,实际上由于 DISTINCT 子句,它没有返回任何结果:
SELECT DISTINCT `threads`.thread_id FROM `threads` LEFT OUTER JOIN `messages` ON `messages`.`thread_id` = `threads`.`thread_id` LEFT OUTER JOIN `users` ON `users`.`user_id` = `threads`.`user_id` WHERE (threads.thread_id='20367' and messages.status=2) ORDER BY messages.pdate LIMIT 1 OFFSET 5
我确定我刚刚在这里弄乱了限制/偏移量。任何帮助表示赞赏。