:as option is used to create named routes in rails. It allows you to specify a name for a route.These helpers make it easier to generate URLs and paths within your application, especially when dealing with resourceful routes.

Example:-

# config/routes.rb
Rails.application.routes.draw do
  resources :posts, as: 'articles'   
  # 'articles' is the custom name for the route helpers
end

In the example above, the :as option is used to specify that the route for articles should be referred to as “articles” in the named route helpers. This means that instead of using post_path(@post) or post_url(@post), you can use article_path(@post) or article_url(@post).

Here’s how you can use these named route helpers in your controllers, views, or other parts of your Rails application:

# In a controller
redirect_to article_path(@post)

# In a view
<%= link_to 'View Post', article_path(@post) %>

This can be used when we want to change the name of our resources in future without having to update all the places where you reference them in your application. It provides an abstraction layer to our routes.

Keep in mind that the :as option is optional, and if you don’t specify it, Rails will automatically generate named route helpers based on the resource name. Using :as is beneficial when you want more control over the names of your route helpers.
With :as option for posts

Without :as option for posts

Another example with match in routes.rb file

match '/search' => posts#search', as: 'post-search', via: %i[get post] # PostsController#search

Above will create post_search_path and post_search_url helpers for “/search” routes with get and post requests.

Support On Demand!

                                         
Ruby on Rails