简体   繁体   中英

Rails Active Record .paginate, Get First page(row), if page (row) specified doesn't exist in database table

In rails 4.2, I am using paginate method to get paginated records from db. I want to get first page, if specified page is not present in the db.

I am using following active record functionality to fetch paged records from database. So If the page number is mentioned 2 and there is only one row in db, the query returns null.

@records = @user.where("some where clause here").paginate(per_page: 1, page: params[:page].presence || 1).

I want to fetch first record if specified page doesn't exist in db. It fetches first record, if params[:page] is empty, but if database doesn't have specified page, it returns nill.

I think this is what you need:

@records = @user.where(title: 'bla').paginate(per_page: 1, page: params[:page].presence || 1).

@results = @records.empty? ? @user.where(title: 'bla').paginate(per_page: 1, page: 1) : @records

This will mean if your @records instance variable has any records it will be returned in @results, and if it doesn't your app will return the first page of results. To make it a bit more readable:

@first_page_records = @user.where(title: 'bla').paginate(per_page: 1, page: 1)
@custom_page_records = @user.where(title: 'bla').paginate(per_page: 1, page: params[:page].presence || 1)

@results = @custom_page_records.empty? ? @first_page_records : @custom_page_records

Although My answer is similar to one posted by Mark. But I still posted it, as it will run an extra query only if original query returns empty records.

@records = @users.valid_users_with_invalid_msg.paginate(per_page: 1, page: params[:page].presence || 1)

if @records.empty?
  @records = @users.valid_users_with_invalid_msg.paginate(per_page: 1, page:  1)
end

Note: I have moved the where clause in scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM