Nick Nizovtsev
Nick Nizovtsev

Reputation: 373

How to check rails route presence in a view

I want something like this:

if has_route?(:controller => 'posts', :action => 'index')
  ...

How I can do this in a view?

---- SOLUTION ----

def has_route? options
  Rails.application.routes.routes.map{|route| route.defaults}.include?(options)
end

Upvotes: 3

Views: 2031

Answers (3)

ipd
ipd

Reputation: 5714

I know this is sort of the inverse of what you want, but you can do something like this:

Rails.application.routes.recognize_path('/posts')

Which will return a hash like this:

{:controller=>"posts", :action=>"index"}

But i don't know of an API for giving it the hash and returning the path.

You could look through the ActionDispatch::Routing::RouteSet API.

Also, note that Rails.application.routes.routes returns an Array of Journey::Routes objects, so you could map this array for the controller/action pairing you want. But it seems like this API should already exist. If not, perhaps it should. :)

Upvotes: 1

megas
megas

Reputation: 21791

Usually the routes test in this way

it "routes to #index" do
  get("/projects").should route_to("projects#index")
end

The scaffold for resource will generate the spec file for testing routes, for example you can look here

Upvotes: 0

Scott S
Scott S

Reputation: 2746

You could try something like respond_to?("[name of rails routing method]")

Upvotes: 0

Related Questions