Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
March 4, 2024
: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.
# 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.
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.