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

后端 未结 3 1175
鱼传尺愫
鱼传尺愫 2021-02-04 15:00

I\'m trying to do a simple family reunion site with: \"posts\", \"families\", \"kids\", and \"pictures\". Ideally I\'d like the routes/relationships to be structured this way:<

3条回答
  •  天涯浪人
    2021-02-04 15:37

    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 :]

提交回复
热议问题