giosakti
giosakti

Reputation: 411

Check to see whether a route exist or not in Rails 3

Can we check/test for existence of a route in Rails?

For example, I want to show a navigation bar that should show all of it's menu URL, regardless the URL exist or not. (to differ between the two, the broken url would use a different styling).

The code to show each menu would look like this:

%li= link_to_unless_current menu.name, :controller => menu.controller, :action => menu.action

However, Rails would complaint and throw an exception, if the supplied controller and action route doesn't exist.

Does Rails have a function to check before I do the aforementioned code?. Perhaps, something that looks like this:

-if some_function_to_check_route_existence?(:controller => menu.controller, :action => menu.action)

EDITED:

Rather than using "controller" and "action" columns for the menu, i use a "url" column instead. Now, I can do something like this:

- if Menu.root
      - for menu in Menu.root.self_and_descendants
        - if menu.url
          %li= link_to_unless_current menu.name, menu.url
        - else
          %li= menu.name

I can also use rails function to determine existence of a route, such as:

Rails.application.routes.recognize_path

Upvotes: 4

Views: 4319

Answers (2)

raymondralibi
raymondralibi

Reputation: 1953

You can use begin rescue instead checking existances

route_exist = true
begin
    url_for(:controller => menu.controller, :action => menu.action)
rescue
    # route not exist
    route_exist = false
end

if route_exist
   ...
else
   ...
end

Upvotes: 0

Sam 山
Sam 山

Reputation: 42865

What about this:

<% link_to @post.title, post_path if post_path %>

Upvotes: 6

Related Questions