I have an Array of various ActiveRecord Objects which are Objects of different Models. One of them is called Team
which is a nested ressource of Department
:
resources :departments do
resources :teams
end
So when I use this in the array.each
like this:
array.each do |element|
link_to element.name, element
end
It throws an error that team_path
doesnt exist whats logical because of nested ressources the route is called department_team_path
but I cant call this method absolutely because I also treat Objets of other Models in this each
.
One posibility I see is to add a Route called team_path whih refers to Team#Show but thats not pretty and also bad for the SEO. Is there another better possibility to link to this and other models in one course?
I wrote my own methods to deal with this problem. They are located in ApplicationHeler
def nested_name(object)
routes = Rails.application.routes.named_routes.to_a
name = nil
routes.each do |r|
name = r[0].to_s if r[1].requirements[:controller] == object.class.to_s.downcase.pluralize && r[1].requirements[:action] == "show"
end
name
end
def nested_object(object)
name = nested_name(object)
parent = name.gsub("_", "").gsub(object.class.to_s.downcase, "")
if object.class.reflect_on_association(parent.to_sym)
return [object.send(parent), object]
else
return object
end
end
So I can do the following:
array.each do |element|
link_to element.name, nested_object(element)
end
It works pretty good for me now,...