Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a rails way to get current route's scope?

If you have a scope in your routes.rb file such as:

scope "/account" do
  resources :items
end

How can you determine if the current page is in the 'account' section? Meaning the following items would be considered in the 'accounts' section?

/account/items
/account/item/1
/account/item/1/edit

I know this is possible by performing string comparisons on request variables but was curious if there is a 'rails way' of determining this information.

Thanks for any input.

like image 411
jeremy.clark Avatar asked Oct 22 '12 18:10

jeremy.clark


People also ask

How do I see routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

What does rake routes do?

rake routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

What are restful routes in Rails?

The Rails router is responsible for redirecting incoming requests to controller actions. The routing module provides URL rewriting in native Ruby. It recognizes URLs and dispatches them as defined in config/routes.

What decides which controller receives Ruby?

Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.


1 Answers

I had the same problem just now.. What I did is add a parameter to the scope:

scope '/me', me_scope: true do
  # ...
end

This way I can look it up in the controller:

class ApplicationController < ActionController::Base
  def me_scope?
    params[:me_scope].eql? true
  end
end

Not the cleanest solution, but it works..

like image 144
Tim Baas Avatar answered Sep 25 '22 04:09

Tim Baas