Search code examples
ruby-on-railsnested-resources

Rails: Getting the Parent Object of a Nested Resource


I have a nested resource that belongs to many different models. For instance:

resources :users do
  resources :histories, only: [:show]
end

resources :publications do
  resources :histories, only: [:show]
end

resources :events do
  resources :histories, only: [:show]
end

In the HistoriesController, I want to find the parent object, though I'm having trouble thinking of a dry way to handle this. At the moment, the best I can come up with is:

if params[:user_id].present?
  @parent = User.find(params[:user_id])
elsif params[:publication_id].present?
  @parent = Publication.find(params[:publication_id])
elsif . . . .

I've got literally dozens of models I have to branch through in this way, which seems sloppy. Is there a better (perhaps baked-in) approach that I'm not considering?


Solution

  • not really a solution but you can get away with

    parent_klasses = %w[user publication comment]
    if klass = parent_klasses.detect { |pk| params[:"#{pk}_id"].present? }
      @parent = klass.camelize.constantize.find params[:"#{klass}_id"]
    end
    

    if you are using a convention between your parameter name and your models