开发者

How do I dynamically create a named_route in rails?

开发者 https://www.devze.com 2023-01-12 21:10 出处:网络
I currently have this in my ApplicationController def account_path eval \"#{current_user.type.downcase}_account_path\"

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 controlle开发者_如何学Gor and view to keep it DRY even though it breaks MVC?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消