Question

I have routes... foo_path, and foo_bar_path. Simple helpers in a link_to.

In the same link, I'm trying to define 2 separate paths...

@foo might be of class Foo, or it might be of class FooBar. It's polymorphic. So, I'd like to build the path with some sort of @foo.class.name.underscore call to prepend to _path.

I can't send it raw with link_to 'foo', "/#{@foo.class.name.underscore}/:id" because I have to send some parameters with it, so only using the route helper works. Unless you know how to send params with that bugger... that'd might simplify things.

Does that make any sense?

Was it helpful?

Solution

Rails will infer the path name from the object type. If you pass a Foo object, it will use foo_path. If you pass a FooBar object, it will use foo_bar_path.

<%= link_to 'foo', foo %>

Assuming foo is one of either a Foo or a FooBar object.

I cover this in-depth in my blog post called "Polymorphic Routes".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top