0

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
davidb
  • 8,884
  • 4
  • 36
  • 72

3 Answers3

2
array.each do |element|
  if element.is_a?(Team)
   link_to element.name, url_for([element.department, element])
  else
    link_to element.name, element
  end
end

as per Rails Guides. Alternatively, you can use resources :departments, :shallow => true but like you mentioned that will give undesirable results for SEO.

  • Of cause that would work in this specific case but it wont work genereally. I wrote my own method now,... will post it soon – davidb Apr 11 '12 at 13:50
1

try this: link_to element.name, url_for(element)

ramigg
  • 1,287
  • 1
  • 15
  • 16
  • Try this (tell me if it helped): http://lostechies.com/joshuaflanagan/2012/03/27/a-smarter-rails-url_for-helper/ – ramigg Apr 11 '12 at 10:59
  • It inspired me but I choose another way because all the information are available and I dont want to write them down a secound time like in the post. – davidb Apr 11 '12 at 13:55
0

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,...

davidb
  • 8,884
  • 4
  • 36
  • 72