Rails 3 - Nested resources and polymorphic paths: OK to two levels, but break at three

左心房为你撑大大i 提交于 2019-12-03 00:04:13

Your code example that limited your nesting to 2 levels is quite near the answer. To avoid duplicate routes for fams->kids and kids, you can use the :only option with a blank array so that the 1st-level kids will not generate routes except in the context of kids->pictures, like so:

resources :posts do
  resources :pictures
end

resources :fams do
  resources :pictures
  resources :kids
end

resources :kids, only: [] do # this will not generate kids routes
   resources :pictures
end

For the above code, you can use the following to construct your polymorphic edit url:

polymorphic_url([fam, picture], action: :edit) # using Ruby 1.9 hash syntax
polymorphic_url([kid, picture], action: :edit)

Have been having this exact same problem for a while. I have it working now, but it isn't beautiful :S

From a nested monster like:

http://localhost:3000/destinations/3/accommodations/3/accommodation_facilities/52

Your params object ends up looking like this:

action: show
id: "52"
destination_id: "3"
accommodation_id: "3"
controller: accommodation_facilities

where "id" represents the current model id (last on the chain) and the other ones have model_name_id

To correctly render another nested link on this page, you need to pass in an array of objects that make up the full path, eg to link to a fictional FacilityType object you'd have to do:

 <%= link_to "New", new_polymorphic_path([@destination, @accommodation, @accommodation_facility, :accommodation_facility_type]) %>

To generate this array from the params object, I use this code in application_helper.rb

def find_parent_models(current_model = nil)
    parents = Array.new

    params.each do |name, value|
      if name =~ /(.+)_id$/
        parents.push $1.classify.constantize.find(value)
      end
    end

    parents.push current_model

    parents
end

Then to automatically make the same link, you can merrily do:

 <%= link_to "New", new_polymorphic_path(find_parent_models(@accommodation_facility).push(:accommodation_facility_type)) %>

Any pointers on making this solution less sketchy are very welcome :]

I can't speak for the polymorphic association problem (probably need more info on the actual error) but you are indeed headed in the right direction by defining your nested resources only one level deep. Here's a popular article by Jamis Buck that has become a reference and that you should probably check out.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!