Rails 创建后重定向到使用 kaminari 分页的记录页面

Rails redirect to record page on pagination with kaminari after creation

在我的一个索引页面中,我有 kaminari 分页。在同一页面上,我还可以通过 form_with 处理创建操作。新记录根据名称保存在适当的位置,因此它可能位于分页的中间。问题是 - 我可以在创建操作后直接重定向到此页面吗?

可以,只需在保存记录后添加重定向,就像在这个例子中,我们正在创建一个 case_file 并在保存后,我们使用 [=16] 的 ID 重定向到索引=].

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

然后在我们的索引控制器上,我们找到保存记录的索引并计算页面,就像这样

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