Get controller name In preceding code, we use the ViewContext object to access the RouteData of the current request. After that, we use the Values property to access the current routing path values. By passing the controller key to the Values property we can get the current controller name.
The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.
controller_name
holds the name of the controller used to serve the current view.
Use controller.controller_name
In the Rails Guides, it says:
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values
ActionController Parameters
So let's say you have a CSS class active
, that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages
controller with an about
action, you can then highlight the link like so in your view:
<li>
<a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
About Us
</a>
</li>
#to get controller name:
<%= controller.controller_name %>
#=> 'users'
#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'
#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'
# or display nicely
<%= debug Rails.application.routes.recognize_path(request.url) %>
reference
controller_path
holds the path of the controller used to serve the current view. (ie: admin/settings
).
and
controller_name
holds the name of the controller used to serve the current view. (ie: settings
).
If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head>
tag
<%= stylesheet_link_tag controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>
Also, to specify the same class CSS on a different controller
Add this line in the body
of application.html.erb
<body class="<%= controller.controller_name %>-<%= controller.action_name %>">
So, now for example I would like to change the p
tag in 'home' controller and 'index' action.
Inside index.scss
file adds.
.nameOfController-nameOfAction <tag> { }
.home-index p {
color:red !important;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With