Tutorial :Dynamically construct RESTful route using Rails



Question:

I'm trying to write a helper method that accepts the name of a plural resource and returns a corresponding link. The essence of the method is:

def get_link(resource)    link_to "#{resource.capitalize}", resource_path  end  

â€"Clearly the resource_path part above doesn't work. What I'd like is to be able to pass foos to get foos_path and bars to get bars_path etc. How can I do that? I can't quite work out the syntax.


Solution:1

  def get_link(resource)    link_to "#{resource.capitalize}", send("#{resource}_path")  end  


Solution:2

  def get_link(resource)    link_to(resource.to_s.titleize, send("#{resource}_path"))  end  

The to_s call on resource is to support passing symbols as resource. So

  get_link("foos")  

will work and also

  get_link(:foos)  


Solution:3

If you want to construct a RESTful route with a member:

send("edit_#{resource}_path".to_sym, @resource)  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »