Brian Armstrong
Brian Armstrong

Reputation: 19863

How do I dynamically create a named_route in rails?

I currently have this in my ApplicationController

def account_path
  eval "#{current_user.type.downcase}_account_path"
end

I use it for redirects, etc. But I also want to use it in the view (for link_to's etc). Is this is a legit case to share code between the controller and view to keep it DRY even though it breaks MVC?

Upvotes: 1

Views: 95

Answers (1)

Shadwell
Shadwell

Reputation: 34774

Yes, I'd say that's a legitimate re-use. The helper_method call is there for a reason so:

helper_method :account_path

will make this available to your views too.

If you prefer not to use eval you could do:

def account_path
  self.send("#{current_user.type.downcase}_account_path")
end

as the _path method is interpreted as a method on the controller.

Upvotes: 2

Related Questions