DEV Community

loading...

Combine `redirect_to` and the `anchor` option

swanson profile image matt swanson Originally published at boringrails.com on ・2 min read

Often you’ll have an application screen like this:

Example company directory

After editing information about an employee, you’ll redirect back to the Company Directory page.

For a bit of extra polish, you can redirect with an anchor to automatically scroll the browser to the recently updated item and maintain your position in the list.

You can combine this with the most underrated Rails helperdom_id – for a really clean solution.

Usage

Your controller will be exactly the same, just tack on the anchor option to the path helper when redirecting.

class EmployeesController < ApplicationController
  include ActionView::RecordIdentifier # adds `dom_id`

  def update
    @company = Company.find(params[:company_id])
    @employee = @company.employees.find(params[:id])

    if @employee.update(employee_params)
      redirect_to companies_path(@company, anchor: dom_id(@employee),
        notice: "Updated #{@employee.name}!"
    else
      render :edit, status: :unprocessable_entity
    end
  end

  private

  def employee_params
    params.require(:employee).permit(:name, :department, :location)
  end
end
Enter fullscreen mode Exit fullscreen mode

Just make sure you use dom_id in your view as well:

<div class="flex flex-col divide-y">
  <%= @company.employees.each do |employee| %>
    <%= content_tag :div, id: dom_id(employee) do %>
      <div class="flex flex-col space-y-2">
        <span class="font-bold"><%= employee.name %></span>
        <span class="text-gray-400">
          <%= employee.department %>
          &middot;
          <%= employee.location %>
        </span>
      </div>
    <% end %>
  <% end %>
</div>
Enter fullscreen mode Exit fullscreen mode

It’s a small tweak, but it’s easy to do and makes your application just a bit more pleasant.

Additional Resources

Rails API: #url_for Options

Rails API: ActionView::RecordIdentifier#dom_id

Rails API: ActionView::TagHelper#content_tag


Discussion (0)

pic
Editor guide