dkruchala
dkruchala

Reputation: 73

Rails redirect to record page on pagination with kaminari after creation

In one of my Index page I have kaminari pagination. On the same page i can also handle a create action by form_with. The new record is saving on place according to name so it could be in the middle of pagination. The question is - can i redirect to this page directly after create action?

Upvotes: 0

Views: 445

Answers (1)

xploshioOn
xploshioOn

Reputation: 4115

Yes you can, just add the redirect after the record is saved, something like in this example, we are creating a case_file and after saved, we redirect to index with the id of our case_file.

def create
  @case_file = CaseFile.new(case_file_params)
  if @case_file.save
    redirect_to case_files_path(to_record: @case_file.id), notice: "#{I18n.t 'created'}"
  else
    render :new
  end
end

then on our index controller, we find the index of the saved record and calculate the page, something like this

def index
  page = 1
  if (params[:page])
    page = params[:page]
  elsif (params[:to_record])
    index = CaseFile.order(:name).pluck(:id).index(params[:to_record])
    page = index/CaseFile.default_per_page + 1 # or if you don't have the default per model, just put the value or get the general default one
  end
  @case_files = CaseFile.all.order(:name).page(page)
end

Upvotes: 1

Related Questions