简体   繁体   中英

Rails 5 find name of parent resource inside child resource controller

Is there any way to identify parent resource name in case of nested resources inside nested resource controller ?

resources :parent do 
  resources :child
end


class ChildController
  def update
      request.parent_resource //this should return :parent (resource name)
   end
end

Thanks in advance.

Logically you'd only use nested resources if Parent has_many Children. Then everything falls into place.

## models
    class Parent < ApplicationRecord
      has_many :children
    end

    class Child < ApplicationRecord
      belongs_to :parent
    end

## routes.rb
    resources :parents do 
      resources :children
    end

## controllers
    class ChildrenController
      def update
          @child = Child.find(params[:id])
          parent = @child.parent
       end
    end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM